其实这个题目就是一个标准的回溯问题
难处是想到将其转换成算法问题(创建棋盘)
package No51_NQueens;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
List<List<String>> res = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
if (n <= 0) {
return null;
}
char[][] board = new char[n][n]; // 棋盘
for (char[] c : board) { // 初始化棋盘
Arrays.fill(c, '.');
}
backTrack(board, 0); // 每一行只摆一个queue 从第0行开始
return res;
}
public void backTrack(char[][] board, int row) {
if (row == board.length) { // 所有queue都有位置了
List<String> temp = charToString(board);
res.add(temp);
return;
}
for (int col = 0; col < board[row].length; col ++) {
if(!isValid(board, row, col)) {
continue;
}
board[row][col] = 'Q';
backTrack(board, row + 1);
board[row][col] = '.';
}
}
/* 判断当前位置是否合法 */
public boolean isValid(char[][] board, int row, int col) {
int cols = board[row].length;
// 判断列
for (int i = 0; i < row; i ++) {
if (board[i][col] == 'Q')
return false;
}
// 判断主对角线
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i --, j-- ) {
if (board[i][j] == 'Q')
return false;
}
// 判断副对角线
for (int i = row - 1, j = col + 1; i >= 0 && j < cols; i --, j ++) {
if (board[i][j] == 'Q')
return false;
}
return true;
}
/* 将字符数组转换成字符串链表 */
public List<String> charToString(char[][] board) {
List<String> temp = new ArrayList<>();
for (char[] c : board) {
temp.add(String.valueOf(c));
}
return temp;
}
public static void main(String[] args) {
Solution s = new Solution();
List<List<String>> res = s.solveNQueens(4);
System.out.println(res);
}
}