[LeetCode][JavaScript]N-Queens

N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens‘ placement, where ‘Q‘ and ‘.‘ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

https://leetcode.com/problems/n-queens/



传说中的N皇后问题,据说AC了这题就能掌握图论搜索,进而称霸算法,然后迎娶白富美,走上人生巅峰。

不就是dfs嘛。

一行行地做dfs。每一轮先找这一行有哪些地方可以放Queen,把这些点置成Q,循环递归这些点,最后不要忘记把默认值‘.‘写回去。

如果到了最后一行,并且可以放得下Queen,这就是一个正确的解。

因为每一行只能放一个,如果遇到放不下的情况,说明已经错了。

找行上的候选人的时候,第一眼看上去要找8个方向。

但首先,行上就不用找了,列方向上和2个斜的方向上只需要找上半部分,因为下面都没开始放Q,肯定不冲突的。

因为js没有二维数组,写了2个方法构造数组,所以看上去代码很长...

 1 /**
 2  * @param {number} n
 3  * @return {string[][]}
 4  */
 5 var solveNQueens = function(n) {
 6     var map = [];
 7     var result = [];
 8     buildMap();
 9     dfs(0);
10     return result;
11
12     function dfs(row){
13         var i = 0, j = 0;
14         var candidates = [];
15         for(i = 0; i < n; i++){
16             if(canPlaceQueen(row, i)){
17                 candidates.push(i);
18             }
19         }
20         if(row === n -1 && candidates.length !== 0){ //found
21             map[row][candidates[0]] = ‘Q‘;
22             result.push(formatMap(map));
23             map[row][candidates[0]] = ‘.‘;
24             return;
25         }
26         for(i = 0; i < candidates.length; i++){
27             map[row][candidates[i]] = ‘Q‘;
28             dfs(row + 1);
29             map[row][candidates[i]] = ‘.‘;
30         }
31     }
32     function canPlaceQueen(x, y){
33         var cell = "";
34         var i = 0, j = 0;
35         for(i = 0; i < n; i++){
36             cell = map[i][y];
37             if(cell === ‘Q‘){
38                 return false;
39             }
40         }
41         for(i = x, j = y; i >=0 && j >= 0; i--, j--){
42             cell = map[i][j];
43             if(cell === ‘Q‘){
44                 return false;
45             }
46         }
47         for(i = x, j = y; i >=0 && j < n; i--, j++){
48             cell = map[i][j];
49             if(cell === ‘Q‘){
50                 return false;
51             }
52         }
53         return true;
54     }
55     function buildMap(){
56         var i = 0, j = 0;
57         for(i = 0; i < n; i++){
58             map[i] = [];
59         }
60         for(i = 0; i < n; i++){
61             for(j = 0; j < n; j++){
62                 map[i][j] = ‘.‘;
63             }
64         }
65     }
66     function formatMap(map){
67         var res = [];
68         var i = 0, j = 0;
69         for(i = 0; i < n; i++){
70             var tmp = "";
71             for(j = 0; j < n; j++){
72                 tmp += map[i][j];
73             }
74             res.push(tmp);
75         }
76         return res;
77     }
78 };
				
时间: 2024-10-03 23:04:09

[LeetCode][JavaScript]N-Queens的相关文章

[LeetCode][JavaScript]Pascal&#39;s Triangle

Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] https://leetcode.com/problems/pascals-triangle/ 杨辉三角. 每行第一个和最后一个是1,其余是pre[i - 1] +

[LeetCode][JavaScript]Insert Interval

https://leetcode.com/problems/insert-interval/ Insert Interval Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start t

[LeetCode][JavaScript]Maximum Subarray

Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray [4,−1,2,1] has the largest sum = 6. https://leetcod

[LeetCode][JavaScript]Coin Change

Coin Change You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination o

[LeetCode][JavaScript]Remove Duplicate Letters

Remove Duplicate Letters Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results

[LeetCode][JavaScript]Additive Number

Additive Number Additive number is a positive integer whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum o

[LeetCode][JavaScript]Unique Binary Search Trees II

Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1

[LeetCode][JavaScript]Binary Tree Preorder Traversal

Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? https://leetcod

[LeetCode][JavaScript]Trapping Rain Water

Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map