|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=51 lang=java |
| 3 | + * |
| 4 | + * [51] N皇后 |
| 5 | + * |
| 6 | + * https://leetcode-cn.com/problems/n-queens/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Hard (70.57%) |
| 10 | + * Likes: 494 |
| 11 | + * Dislikes: 0 |
| 12 | + * Total Accepted: 54.3K |
| 13 | + * Total Submissions: 77K |
| 14 | + * Testcase Example: '4' |
| 15 | + * |
| 16 | + * n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 |
| 17 | + * |
| 18 | + * |
| 19 | + * |
| 20 | + * 上图为 8 皇后问题的一种解法。 |
| 21 | + * |
| 22 | + * 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 |
| 23 | + * |
| 24 | + * 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。 |
| 25 | + * |
| 26 | + * 示例: |
| 27 | + * |
| 28 | + * 输入: 4 |
| 29 | + * 输出: [ |
| 30 | + * [".Q..", // 解法 1 |
| 31 | + * "...Q", |
| 32 | + * "Q...", |
| 33 | + * "..Q."], |
| 34 | + * |
| 35 | + * ["..Q.", // 解法 2 |
| 36 | + * "Q...", |
| 37 | + * "...Q", |
| 38 | + * ".Q.."] |
| 39 | + * ] |
| 40 | + * 解释: 4 皇后问题存在两个不同的解法。 |
| 41 | + * |
| 42 | + * |
| 43 | + * |
| 44 | + * |
| 45 | + * 提示: |
| 46 | + * |
| 47 | + * |
| 48 | + * |
| 49 | + * 皇后,是国际象棋中的棋子,意味着国王的妻子。皇后只做一件事,那就是“吃子”。当她遇见可以吃的棋子时,就迅速冲上去吃掉棋子。当然,她横、竖、斜都可走一到七步,可进可退。(引用自 |
| 50 | + * 百度百科 - 皇后 ) |
| 51 | + * |
| 52 | + * |
| 53 | + */ |
| 54 | + |
| 55 | +// @lc code=start |
| 56 | +class Solution { |
| 57 | + public List<List<String>> solveNQueens(int n) { |
| 58 | + List<List<String>> boards = new ArrayList<>(); |
| 59 | + if(n < 1) return boards; |
| 60 | + int col = 0, aDiag = 0, diag = 0; |
| 61 | + |
| 62 | + dfs(n, 0, new ArrayList<>(), boards, col, aDiag, diag); |
| 63 | + return boards; |
| 64 | + } |
| 65 | + |
| 66 | + private void dfs(int n, int row, List<String> board, List<List<String>> boards,int col, int aDiag, int diag){ |
| 67 | + //recursion terminator |
| 68 | + if(row >= n) { |
| 69 | + boards.add(new ArrayList<>(board)); |
| 70 | + return; |
| 71 | + } |
| 72 | + //get available spots for the current row |
| 73 | + int bits = (~(col | aDiag | diag)) & ((1 << n) - 1); |
| 74 | + |
| 75 | + while(bits > 0){ |
| 76 | + int p = bits & -bits; |
| 77 | + int pos = Integer.toBinaryString(p).length(); |
| 78 | + |
| 79 | + char[] boardRow = new char[n]; |
| 80 | + Arrays.fill(boardRow, '.'); |
| 81 | + boardRow[n - pos] = 'Q'; |
| 82 | + |
| 83 | + board.add(String.valueOf(boardRow)); |
| 84 | + dfs(n, row + 1, board, boards, col | p, (aDiag | p) << 1, (diag | p) >> 1); |
| 85 | + board.remove(board.size() - 1); |
| 86 | + |
| 87 | + bits &= bits - 1; |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | +// @lc code=end |
| 92 | + |
0 commit comments