力扣LeetCode #51 N皇后(SolveNQueens)
- 题目描述
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
提示: 皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。
- 示例示例:
输入:4 输出:
-
解法 1 [ [".Q…", “…Q”, “Q…”, “…Q.”], 解法 2 ["…Q.", “Q…”, “…Q”, “.Q…”] ]
解释: 4 皇后问题存在两个不同的解法。
- 思路分析
就是回溯+剪枝,在尝试的过程中不断去掉不可能的情况。因为要同一行、同一列、同一斜线上至多只能有一个皇后,因此考虑用三个数组,分别保存列信息、左下到右上的斜方向信息和左上到右下的斜方向信息。每到一行,就看还有哪些位置是可以放皇后的:如果没有,则回到上一行;如果有,就放入,并进入下一行。
- JAVA实现
class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> solu = new ArrayList(); int[][] matrix = new int[n+1][n+1]; int[] columns = new int[n+1]; int[] slopes_btm = new int[2*n]; //1~2n-1对应从左下到右上的斜线 int[] slopes_up = new int[2*n]; //1~2n-1对应从左上到右下的斜线 for(int i=0;i<2*n;i++) { slopes_btm[i] = 0; slopes_up[i] = 0; } for(int i=0;i<n+1;i++) { columns[i] = 0; for(int j=0;j<n+1;j++) { matrix[i][j] = 0; } } Queen(matrix, columns, slopes_btm, slopes_up, solu, 1); //k:准备放第k行,还没有放 return solu; } public void Queen(int[][] matrix, int[] columns, int[] slopes_btm, int[] slopes_up, List<List<String>> solu, int k) { if(k==matrix.length) { List<String> ans = new ArrayList(); for(int i=1;i<k;i++) { String s =""; for(int j=1;j<k;j++) { if(matrix[i][j] == 0) s+="."; else s+="Q"; } ans.add(s); } solu.add(new ArrayList(ans)); } else { int n = matrix.length-1; for(int j=1;j<n+1;j++) { if(columns[j] == 0) { //该列是否空着 int slop_btm = 0, slop_up = 0; slop_btm = k>=j ? n-(k-j) : n+j-k; slop_up = k+j-1; if(slopes_btm[slop_btm] == 0 && slopes_up[slop_up] == 0) { //说明找到一个满足的位置 columns[j] = 1; slopes_btm[slop_btm] = 1; slopes_up[slop_up] = 1; matrix[k][j] = 1; Queen(matrix, columns, slopes_btm, slopes_up, solu, k+1); columns[j] = 0; slopes_btm[slop_btm] = 0; slopes_up[slop_up] = 0; matrix[k][j] = 0; } } } } } }