本文共 1917 字,大约阅读时间需要 6 分钟。
package javatask;public class EightQueenO { private int[][]map; private int len; private int[]C; private int tol; public static void main(String[] args) { new EightQueenO().run(); } public EightQueenO() { len = 8; C = new int[len];//记录当前行可放置的列 tol = 0; } public void run() { search(0); System.out.println("total = " + tol); } public boolean isOk(int row, int col) { for(int j = 0; j < row; j++ ) { if(C[j] == col || C[j]+ j == col+row || C[j]-j == col-row) {//只需要判断当前行以前的对角线和列即可 return false; } } return true; } public void search(int cur) { if(cur == len) { tol++; //只有到达 这里时候 才是完成了 八皇后 for(int i = 0; i < len; i++ ) { for(int j = 0; j < len; j++ ) { if(C[i] == j) System.out.print(1+" "); else System.out.print(0 +" "); } System.out.println(); } System.out.println("***************"); } else { for(int i = 0; i < len; i++ ) { C[cur] = i;//这里保证了 最终的值一定是构成8皇后时候的值(因为其值不断被修改直到完成所有行) if(isOk(cur, i)) { // map[cur][i] = 1;//有的不能构成八皇后但是仍然 在末尾之前的位置满足 也被记录了 search(cur+1); //所以用map记录是错误的 } } }// for(int i = 0; i < len; i++ ) {// int ok = 1;// C[cur] = i;// for(int j = 0; j < cur; j++ ) {// if(C[j] == C[cur]|| C[j]+ j == C[cur]+cur || C[j]-j == C[cur]-cur) {// ok = 0; break;// }// }// if(ok == 1) search(cur+1);// } }}
中间的dfs部分可以换成
for(int i = 0; i < len; i++ ) { if(isOk(cur, i)) { vis[cur] = i; search(cur+1); vis[cur] = 0;//保证 只有成功的时候才会被记录 然后 输出后 立刻 清零 } }
C++ :
#includeusing namespace std;const int N = 1010;int tol;int C[N];int n; void dfs(int cur){ if(cur == n){ tol++; return ; } else for(int j = 0; j < n; ++j){ C[cur] = j; bool ok = 1; for(int i = 0; i < cur; ++i){ if(C[cur] == C[i] || cur-C[cur] == i-C[i] || cur + C[cur] == i+C[i]){ ok = 0; break; } } if(ok) dfs(cur+1); }}int main() { cin >> n; dfs(0); cout << tol << endl; return 0; }
转载地址:http://roimi.baihongyu.com/