leeetcode 52. N皇后 II-java实现
题目所属分类
dfs模板题
原题链接
n 皇后问题 研究的是如何将 n 个皇后放置在 n × n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。
代码案例:
题解
ans要是放到全局变量时候就是错误的
class Solution {
static int N = 20;
static char[][] g = new char[N][N];
static boolean[] col = new boolean[N];
static boolean[] dg = new boolean[N];//正斜
static boolean[] udg = new boolean[N];//反斜
static int ans ;
public int totalNQueens(int n) {
ans = 0;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < n ; j++){
g[i][j] = '.';
}
}
dfs( 0 , n );
return ans ;
}
public void dfs(int y , int n ){
if(y == n ){
ans++;
return ;
}
for(int x = 0 ; x < n ; x++){
if(!col[x] && !dg[y-x+n] & !udg[y+x]){
g[y][x] = 'Q';
col[x] = dg[y - x + n] = udg[x + y] = true;
dfs(y + 1,n);
col[x] = dg[y - x + n] = udg[x + y] = false;
g[y][x] = '.';
}
}
}
}


浙公网安备 33010602011771号