原题:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
回溯法代码:
public class Solution {
boolean able_place(boolean[][] matrix, int place_row, int place_col){
for(int row = place_row-1; row >= 0; --row){
if(matrix[row][place_col] == true) return false;
}
for(int row = place_row-1,col = place_col-1; row >= 0 && col >= 0; --row,--col){
if(matrix[row][col] == true) return false;
}
for(int row = place_row-1,col = place_col+1; row >= 0 && col < matrix[0].length; --row,++col){
if(matrix[row][col] == true) return false;
}
return true;
}
int NQueens(int n, int place_row, boolean[][] matrix){
if(place_row >= matrix.length) return 0;
int count = 0;
for(int j = 0; j < matrix[0].length; ++j){
if(able_place(matrix,place_row,j)){
matrix[place_row][j] = true;
if(place_row == matrix.length-1){
return 1;
}
count = count + NQueens(n,place_row+1,matrix);
matrix[place_row][j] = false;
}
}
return count;
}
public int totalNQueens(int n) {
return NQueens(n,0,new boolean[n][n]);
}
}
感觉用分治算法优化不了啊,之前写错过一次,还以为下面这样写能优化速率呢
void adjust_matrix(int place_row, int place_col, boolean[][]matrix, boolean place){
for(int row = place_row; row < matrix.length; ++row){
matrix[row][place_col] = place;
}
for(int col = place_col+1, row = place_row+1; col < matrix[0].length && row < matrix.length; ++col,++row){
matrix[row][col] = place;
}
for(int col = place_col-1, row = place_row+1; col >=0 && row < matrix.length; --col,++row){
matrix[row][col] = place;
}
}
int NQueens(int n, int place_row, boolean[][] matrix){
if(place_row >= matrix.length) return 0;
int count = 0;
for(int j = 0; j < matrix[0].length; ++j){
if(!matrix[place_row][j]){
adjust_matrix(place_row,j,matrix,true);
if(place_row == matrix.length-1){
return 1;
}
count = count + NQueens(n,place_row+1,matrix);
// count = 1 + NQueens(n,place_row+1,matrix);
adjust_matrix(place_row,j,matrix,false);
}
}
return count;
}
public int totalNQueens(int n) {
return NQueens(n,0,new boolean[n][n]);
}