题解 | #N皇后问题#
N皇后问题
http://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
import java.util.*;
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
private int res= 0;
public int Nqueen (int n) {
find(n,0,pos);
return res;
if(row == n){
res++;
return;
}
for(int i = 0;i<n;i++){
if(isValid(pos,row,i)){
pos[row] = i;
find(n,row+1,pos);
pos[row] = -1;
}
}
for(int i = 0;i<row;i++){
if(col == pos[i]||Math.abs(col-pos[i])==Math.abs(row-i)){
return false;
}
}
return true;
}
}
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
private int res= 0;
public int Nqueen (int n) {
// write code here
//下标为行,值为列
int[] pos = new int[n];
//初始化
Arrays.fill(pos,-1);find(n,0,pos);
return res;
}
//回溯算法
public void find(int n,int row,int[] pos){if(row == n){
res++;
return;
}
for(int i = 0;i<n;i++){
if(isValid(pos,row,i)){
pos[row] = i;
find(n,row+1,pos);
pos[row] = -1;
}
}
}
//判断前row行与本行是否同列或者同一斜线
public boolean isValid(int[] pos,int row,int col){for(int i = 0;i<row;i++){
if(col == pos[i]||Math.abs(col-pos[i])==Math.abs(row-i)){
return false;
}
}
return true;
}
}