N皇后II
题目描述:
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。给你一个整数 n ,返回 n 皇后问题不同的解决方案的数量。提示:1 <= n <= 9皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上
class Solution {
private int result;
private List<String> temp;
private String space;
private int n;
public int totalNQueens(int n) {
// 初始化
this.temp = new ArrayList<String>();
this.n = n;
this.space = "";
for(int i = 0 ; i<n ; i++) this.space += ".";
for(int i = 0 ; i<n ; i++){
this.temp.add(space);
}
// 回溯算法
Backtracking(0); // 行优先
return result;
}
private void Backtracking(int count){
if(count == this.n){
this.result ++ ;
return;
}
for(int i = 0 ; i<this.n ; i++){
if(check(count,i)){
String temp = this.temp.get(count).substring(0,i)+"Q"
+this.temp.get(count).substring(i+1,this.n); // 局部变量
this.temp.set(count,temp);
Backtracking(count+1);
this.temp.set(count,this.space); // 还原
}
}
}
private boolean check(int x,int y){
for(int i = 0 ; i<x ; i++){ // 行遍历
for(int j = 0 ; j<this.n ; j++){ // 列遍历
if(this.temp.get(i).charAt(j) == 'Q'
&&( Math.abs(y-j) == Math.abs(x-i) // 斜线上相互攻击
|| j == y)) // 纵线上相互攻击
return false;
}
}
return true;
}
}
典型的回溯算法,这题读者只要能自己独立解决该题,一般这题就没有问题了,如果读者有疑问的地方,欢迎你的留言。