题目描述
- 经典题了…但是大一敲过后就再没碰过了。结果面试还是会问= =,今天补一下~
思路 && 代码
- 还是挺清晰的,要点如下:
- 使用 DFS,找到一个了再继续找
- 对每一行,逐列进行可行点选择
- 放置点可行判断:【对低行进行】列、45度、135度判断
- 答案格式转换,char[][] 变成 List
class Solution {List<List<String>> ans = new ArrayList<>(); char[][] graph;public List<List<String>> solveNQueens(int n) {graph = new char[n][n];for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {graph[i][j] = '.';}}dfs(0);return ans;}void dfs(int row) {if(row == graph.length) {ans.add(array2List());}for(int col = 0; col < graph[0].length; col++) {if(judge(row, col)) {graph[row][col] = 'Q';dfs(row + 1);graph[row][col] = '.';}}}boolean judge(int row, int col) {for(int i = row - 1; i >= 0; i--) {if(graph[i][col] == 'Q') {return false;}}for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {if(graph[i][j] == 'Q') {return false;}}for(int i = row - 1, j = col + 1; i >= 0 && j < graph[0].length; i--, j++) {if(graph[i][j] == 'Q') {return false;}}return true;}List<String> array2List() {List<String> list = new ArrayList<>();for(int i = 0; i < graph.length; i++) {list.add(String.valueOf(graph[i]));}return list;}
}