卖萌的弱渣

I am stupid, I am hungry.

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.

Example:

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

1
2
3
4
5
6
7
8
9
10
11
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

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

Solution

  • DFS: visited[n] 记录当前q都在什么位置
(N-Queens.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        if n < 1:
            return []
        # 记录每一行当前Q在哪里
        visited = [-1]*n
        ret = []
        self.rec([],ret,visited,n,0)
        return ret



    def rec(self,board,ret,visited,n,index):

        def check(visited,row,col):
            for i in range(row):
                if visited[i] == col or abs(i-row) == abs(col-visited[i]):
                    return False
            return True


        if index == n:
            ret.append(board[:])
            return

        for j in range(n):
            # 第[index][j]可以被放queen
            if check(visited,index,j):
                visited[index] = j

                newstr = "."*n
                self.rec(board+[newstr[:j]+'Q'+newstr[j+1:]],ret,visited,n,index+1)