N皇后
题目描述:
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。提示:1 <= n <= 9皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上
示例
class Solution {
private List<List<String>> result;
private List<String> temp;
private String space;
private int n;
public List<List<String>> solveNQueens(int n) {
// 初始化
this.result = new ArrayList<List<String>>();
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 this.result;
}
private void Backtracking(int count){
if(count == this.n){
List<String> temp = new ArrayList<String>(); // 局部变量
for(int i = 0 ; i<n ; i++) temp.add(this.temp.get(i));
this.result.add(temp);
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;
}
}
典型的回溯算法,这里采用行优先,每一层都遍历所有列位置,如果该层当前列和前面所有的皇后有冲突(行、纵、斜位置具有皇后),则直接跳过当前列,继续遍历下一列,如果该层所有列都遍历完毕,但是都没有可行解,则回溯到上一层,然后开始上一层的下一列,重复以上步骤,直到到达最后一层都具有可行解即可。读者有疑问的地方,欢迎留言。