本文主要是介绍poj 1321 :棋盘问题 (dfs),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文:
http://blog.sina.com.cn/s/blog_6635898a0100hu5n.html
直接上代码:
/*代码1*/
#include<iostream>
#include<cstring>
using namespace std;
const int MAX = 10;bool board[MAX][MAX], row[MAX], col[MAX];
int len, num, ans, n, k;void dfs(int depth, int start_line){if(depth == k){ans ++;return;}for(int i = start_line + 1; i <= n; i ++){for(int j = 1; j <= n; j ++){if(board[i][j] == true && row[i] == false && col[j] == false){row[i] = true; col[j] = true;dfs(depth + 1, i);row[i] = false; col[j] = false;}}}
}int main(){int i, j;char c;while(cin >> n>> k, n!= -1){ans = 0;memset(board, false, sizeof(board));for(i = 1; i <= n; i ++)for(int j = 1; j <= n; j ++){cin >> c;if(c == '#'){board[i][j] = true;}}memset(row, false, sizeof(row));memset(col, false, sizeof(col));int start_line = n - k + 1;for(i=1; i <= start_line; i ++)for(j = 1; j <= n; j ++)if(board[i][j] == true){row[i] = true; col[j] = true;dfs(1, i);row[i] = false; col[j] = false;}cout << ans << endl;}return(0);
}
/*代码2*/
#include<iostream>
using namespace std;
int n, k, temp;
bool b[10][10];
int c[8][2];void deal(int row, int rol, int step);
int duan();int main(){char a[10];while(cin >> n>> k, n!= -1){temp=0;for(int i = 1; i <= n; i ++){cin >> a;for(int j = 1; j <= n; j ++){if(a[j-1] == '#'){b[i][j] = true;}else{b[i][j] = false;}}}deal(1, 1, 0);cout << temp << endl;}return(0);
}
void deal(int row, int rol, int step){if(step == k){temp += duan();return;}if(row > n ){return;}if(b[row][rol]){c[step][0] = row;c[step][1] = rol;deal(row + 1, 1, step + 1);}if(rol < n) deal(row, rol + 1, step);else deal(row + 1, 1, step);
}
int duan(){for(int i = 0; i < k; i ++){for(int j = i + 1; j < k; j ++){if(c[i][0] == c[j][0] || c[i][1] == c[j][1])return(0);}}return(1);
}
这篇关于poj 1321 :棋盘问题 (dfs)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!