八皇后问题
经典的八皇后问题。。
#define LEN 8 int count = 0; void eightQueen(int chess[][8], int row); int isSafe(int chess[][8], int row, int col); int main(int argc, char *argv[]) { int chess[LEN][LEN]; int i, j; for(i = 0; i<LEN; i++) { for(j = 0; j < LEN; j++) { chess[i][j] = 0; } } eightQueen(chess, 0); printf("共有%d种方案", count); return 0; } void eightQueen(int (*chess)[8], const int row) { int chess2[LEN][LEN]; int i,j, k; for(i = 0; i< LEN; i++) { for(j = 0; j< LEN; j++) { //printf("%d ", *(*((chess)+i)+j) ); chess2[i][j] = *(*(chess+i)+j); } } if(row==LEN) { count += 1; printf("第 %d 种方案\n", count); for(i = 0; i< LEN; i++) { for(j = 0; j< LEN; j++) { printf("%d ", chess2[i][j]); } printf("\n"); } printf("\n"); }else { for(j = 0; j<LEN; j++) { for(k = 0; k<j; k++) { chess2[row][k] = 0; } if(!isSafe(chess2, row, j)) { chess2[row][j] = 1; eightQueen(chess2, row+1); } } } } int isSafe(int (*chess)[8], const int row, const int col) { int i,j,res = 0; for(i = row; i>=0; i--) { if(*(*(chess+i)+col) == 1) { res = 1; break; } } if(res == 1) { return res; } for(i = row-1, j = col-1; i>=0 && j>=0; i--, j--) { if(*(*(chess+i)+j) == 1) { res = 1; break; } } if(res == 1) { return res; } for(i = row-1, j = col+1; i>=0 && j< LEN; i--, j++) { if(*(*(chess+i)+j) == 1) { res = 1; break; } } if(res == 1) { return res; } return 0; }
eightQueen函数中,用k作循环的那一段超级重要,要不然每一行的结果之间就会相互影响。。。。。。