diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\233\236\346\272\257\347\256\227\346\263\225\350\257\246\350\247\243\344\277\256\350\256\242\347\211\210.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\233\236\346\272\257\347\256\227\346\263\225\350\257\246\350\247\243\344\277\256\350\256\242\347\211\210.md" index 37c373239c9ccd71893f53370c163d98b92c73db..034a9fe2d2557bece69938a20d770ccdef3f7262 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\233\236\346\272\257\347\256\227\346\263\225\350\257\246\350\247\243\344\277\256\350\256\242\347\211\210.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\233\236\346\272\257\347\256\227\346\263\225\350\257\246\350\247\243\344\277\256\350\256\242\347\211\210.md" @@ -309,4 +309,67 @@ def backtrack(...):

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +由[kepler-zc](https://github.com/kepler-zc) 提供 51.N皇后 Java 解法代码: +```java +class solution { + private List> res = new ArrayList<>(); + + // 输入棋盘边长 n,返回所有合法的放置 + public List> solveNQueens(int n){ + // '.'表示空,'Q'表示皇后,初始化空棋盘 + char[][] chess = new char[n][n]; + for (int i = 0; i < n; i++) { + Arrays.fill(chess[i], '.'); + } + // 已经不能放置皇后的列(被占用) + boolean[] usedCol = new boolean[n]; + // 已经不能放置皇后的正斜线 , 按右上角到左下角排列 , 共2n-1条 + boolean[] usedSlash = new boolean[2*n-1]; + // 已经不能放置皇后的反斜线 , 按左上角到右下角排列 , 共2n-1条 + boolean[] usedBackSlash = new boolean[2*n-1]; + backtrack(chess, 0, usedCol, usedSlash, usedBackSlash); + return res; + } + + // 路径:chess 中小于 row 的那些行都已经成功放置了皇后 + // 选择列表:第 row 行的所有列都是放置皇后的选择 + // 结束条件:row 超过 棋盘最后一行 + private void backtrack(char[][] chess, int row, boolean[] usedCol, boolean[] usedSlash, boolean[] usedBackSlash) { + // 触发结束条件 + if (row == chess.length){ + res.add(construct(chess)); + return; + } + for (int col = 0; col < chess.length; col++) { + // 对合法选择进行回溯操作 + // 分别检查列,左上方, 右上方是否存在皇后冲突,都不冲突集为合法选择。 + if (!usedCol[col] && !usedSlash[row-col+usedCol.length-1] && !usedBackSlash[col+row]){ + // 做选择 + chess[row][col] = 'Q'; + usedCol[col] = true; + // 对坐标为[i,j]的点对应的正斜线和反斜线的索引分别为:row-col+n-1; col+row + usedSlash[row-col+chess.length-1] = true; + usedBackSlash[col+row] = true; + // 进入下一行 + backtrack(chess, row+1, usedCol,usedSlash, usedBackSlash); + // 撤销选择 + chess[row][col] = '.'; + usedCol[col] = false; + usedSlash[row-col+chess.length-1] = false; + usedBackSlash[col+row] = false; + } + } + } + + private List construct(char[][] chess) { + // 数组转List + List path = new ArrayList<>(); + for (char[] chars : chess) { + path.add(new String(chars)); + } + return path; + } +} +``` \ No newline at end of file