简单的dfs,非最优解,胜在思路清晰
class Solution {
int res = 0;
public int totalNQueens(int n) {
boolean[][] grid = new boolean[n][n];
dfs(grid,0);
return res;
}
public void dfs(boolean[][] grid,int row){
if(row == grid.length){
++res;
return;
}
//遍历每一行
for(int i=0 ; i<grid.length ; i++){
if(isValid(grid,row,i)){
grid[row][i] = true;
//递归判断下一行
dfs(grid,row+1);
grid[row][i] = false;
}
}
}
int[][] dirs = {{1,0},{1,1},{1,-1},{0,-1},{0,1},{-1,-1},{-1,0},{-1,1}};
//判断该格是否可以放置棋子
public boolean isValid(boolean[][] grid,int x,int y){
int n = grid.length;
for(int[] dir : dirs){
int i=x;
int j=y;
while(i>=0 && j>=0 && i<n && j<n){
if(grid[i][j]){
return false;
}
i+=dir[0];
j+=dir[1];
}
}
return true;
}
}
来源:https://blog.csdn.net/weixin_44601714/article/details/102732582