题目描述:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of then-queens' placement, where'Q'and'.'both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
思路解析:
- 国际象棋的皇后是可以前后左右斜上斜下移动的。
- 首先判断给出的n是不是合法的,不合法即小于等于0时,返回空的ArrayList
- 声明一个一维数组,下标表示行,下标对应的值表示列。这个数组用来表示皇后的位置
- 用一个方法表示象棋中填入每一行的皇后,如果填入的行已经和n相等了,证明可以存入字符串中了,所以此时,需要有StringBuilder来每次填入,如果是皇后就append 'Q',否则是‘.’
- 还要有一个方法判断新加入的皇后的位置是否是合法的,isValue,除了重复的情况,还要看斜着的情况。
代码:
import java.util.*;
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
if(n<=0)
return res;
int[] columnVal = new int[n];
DFS_helper(n,res,0,columnVal);
return res;
}
public void DFS_helper(int nQueens,ArrayList<String[]> res,int row,int[] columnVal){
if(row == nQueens){
String[] unit = new String[nQueens];
for(int i=0;i<nQueens;i++){
StringBuilder s = new StringBuilder();
for(int j=0;j<nQueens;j++){
if(j==columnVal[i])
s.append("Q");
else
s.append(".");
}
unit[i]=s.toString();
}
res.add(unit);
}else{
for(int i=0;i<nQueens;i++){
columnVal[row] = i;
if(isValid(row,columnVal))
DFS_helper(nQueens,res,row+1,columnVal);
}
}
}
public boolean isValid(int row,int[] columnVal){
for(int i=0;i<row;i++){
if(columnVal[row]==columnVal[i] || Math.abs(columnVal[row]-columnVal[i]) == row-i)
return false;
}
return true;
}
}