又一个经典问题,貌似很多公司笔试都考过这个问题的非递归程序求解。下面是我的递归与非递归程序,个人感觉程序逻辑还是比较清晰:)。
int board[8][8]; int cnt = 0; bool isValid(int i, int j) { int k; for(k = 0; k < 8; ++k) if(k != j && board[i][k]) return false; for(k = 0; k < 8; ++k) if(k != i && board[k][j]) return false; for(k = 1; k < 8 && i-k >= 0 && j-k >= 0; ++k) if(board[i-k][j-k]) return false; for(k = 1; k < 8 && i-k >= 0 && j+k < 8; ++k) if(board[i-k][j+k]) return false; return true; } void queen_rec(int row) { if(row == 8) { for(int i = 0; i < 8; ++i) for(int j = 0; j < 8; ++j) if(board[i][j]) printf("%d %d\n", i, j); printf("\n"); ++cnt; } else { for(int i = 0; i < 8; ++i) { if(isValid(row, i)) { board[row][i] = 1; queen_rec(row+1); board[row][i] = 0; } } } } void queen_nonrec() {
//use stack to hold the previous valid position of each row int stack[8], row; for(row = 0; row < 8; ++row) stack[row] = -1; row = 0; //the row variable will decrease by 1 whenever backtracking happens. //Finally, the row variable will become -1 and the loop should end there. while(row >= 0) { if(row == 8) { for(int i = 0; i < 8; ++i) { for(int j = 0; j < 8; ++j) if(board[i][j]) printf("%2d",1); else printf("%2d", 0); printf("\n"); } printf("\n"); ++cnt; --row; } else { //recover current position to be valid if(stack[row] >= 0 && stack[row] < 8) board[row][stack[row]] = 0; //try to find the next position available ++stack[row]; while(stack[row] < 8 && !isValid(row, stack[row])) ++stack[row]; //when come to the end of current row, set the position index of current row back to -1 and go to the upper row if(stack[row] >= 8) {stack[row] = -1; --row;} else { //found a valid position, go to the next row board[row][stack[row]] = 1; ++row; } } } }