一起学习LeetCode热题100道(62/100)

62.N 皇后(学习)

按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。

示例 1:
在这里插入图片描述
输入:n = 4
输出:[[“.Q…”,“…Q”,“Q…”,“…Q.”],[“…Q.”,“Q…”,“…Q”,“.Q…”]]
解释:如上图所示,4 皇后问题存在两个不同的解法。

示例 2:
输入:n = 1
输出:[[“Q”]]

提示:
1 <= n <= 9

解析:
一、初始化
在函数内部,首先初始化几个关键的数据结构:

1.res:一个空数组,用于存储所有有效的N皇后解决方案。
2.board:一个n x n的二维数组,初始时每个位置都是空位(‘.’)。这个数组代表棋盘。
3.cols、diag1、diag2:分别用于记录列、主对角线和副对角线的占用情况。它们都是长度为n或2n-1的布尔数组,初始时所有位置都是false。

二、辅助函数:isValid
这个函数用于检查在(row, col)位置放置皇后是否合法。它检查三个条件:
1.当前列是否已被占用(cols[col])。
2.当前位置的主对角线是否已被占用(通过row - col + n - 1计算得到的索引d1)。
3.当前位置的副对角线是否已被占用(通过row + col计算得到的索引d2,注意这里可能需要调整索引以适配数组边界)。
4.如果以上任何一个条件不满足(即返回false),则不能在(row, col)位置放置皇后。

三、主递归函数:placeQueen
这个函数是解决N皇后问题的核心。它使用回溯法来尝试在棋盘的每一行放置皇后。
1.基准情况:如果row等于n,说明已经成功地在棋盘上放置了n个皇后,且没有相互攻击的情况。此时,将当前棋盘状态转换为一个解决方案(即一个二维数组,其中每个子数组代表棋盘的一行,并用’Q’和’.'表示皇后和空位),并将其添加到res数组中。
2.递归情况:如果row小于n,则遍历当前行的每一列(col从0到n-1)。对于每一列,首先检查(row, col)位置是否合法(调用isValid函数)。3.如果合法,则在该位置放置皇后(更新board、cols、diag1、diag2),并递归调用placeQueen(row + 1)来尝试放置下一个皇后。递归返回后,需要进行回溯,即将当前位置的皇后移除,并恢复相关列和对角线的占用状态,以便尝试其他可能的解决方案。

四、开始递归
1.通过调用placeQueen(0)开始递归过程。这是因为在棋盘的第一行开始尝试放置第一个皇后。

五、返回结果
1.当所有可能的解决方案都被找到并存储在res数组中后,函数返回res。

var solveNQueens = function (n) {
    let res = [];
    let board = new Array(n).fill('.').map(() => new Array(n).fill('.'));
    let cols = new Array(n).fill(false); // 标记列  
    let diag1 = new Array(2 * n - 1).fill(false); // 主对角线  
    let diag2 = new Array(2 * n - 1).fill(false); // 副对角线  

    function isValid(row, col) {
        // 检查列  
        if (cols[col]) return false;
        // 检查两个对角线  
        let d1 = row - col + n - 1;
        let d2 = row + col;
        if (diag1[d1] || diag2[d2]) return false;
        return true;
    }

    function placeQueen(row) {
        if (row === n) {
            let solution = [];
            for (let i = 0; i < n; i++) {
                let rowStr = '';
                for (let j = 0; j < n; j++) {
                    rowStr += board[i][j] === 'Q' ? 'Q' : '.';
                }
                solution.push(rowStr);
            }
            res.push(solution);
            return;
        }

        for (let col = 0; col < n; col++) {
            if (isValid(row, col)) {
                board[row][col] = 'Q';
                cols[col] = true;
                let d1 = row - col + n - 1;
                let d2 = row + col;
                diag1[d1] = true;
                diag2[d2] = true;

                placeQueen(row + 1);

                // 回溯  
                board[row][col] = '.';
                cols[col] = false;
                diag1[d1] = false;
                diag2[d2] = false;
            }
        }
    }

    placeQueen(0);
    return res;
};
  • 16
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值