N皇后的详细解法可以看leetcode 每日一题 51 N皇后,这里只需要把 i==chars.length
下的添加解法改为 count++
即可。
package com.company;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class lc52 {
int count = 0;
public int totalNQueens(int n) {
if(n==0)return 0;
char[][] chars= new char[n][n];
for(char[] ch : chars){
Arrays.fill(ch,'.');
}
boolean[] column = new boolean[n];
boolean[] slash = new boolean[2*n-1];
boolean[] backslash = new boolean[2*n-1];
find(chars,column,slash,backslash,0);
return count;
}
public void find(char[][] chars,boolean[] column,boolean[] slash,boolean[] backslash,int i){
if(i==chars.length){
count++;
}else{
for (int j = 0; j < chars.length; j++) {
int slashTemp = i+j;
int backslashTemp = chars.length-1-j+i;
if(!column[j]&&!slash[slashTemp]&&!backslash[backslashTemp]){
chars[i][j] = 'Q';
column[j] = true;
slash[slashTemp] = true;
backslash[backslashTemp] = true;
find(chars,column,slash,backslash,i+1);
chars[i][j] = '.';
column[j] = false;
slash[slashTemp] = false;
backslash[backslashTemp] = false;
}
}
}
}
}