Leetcode-51N-Queens

51. 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.

Leetcode-51N-Queens_第1张图片
image

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.

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

My Solution:

import copy
class Solution:
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        result = []
        board = [[0 * m for m in range(n)] for m in range(n)]
        row = 0
        self.get_board(n, row, result, board)
        for r in result:
            for i in range(len(r)):
                r[i] = ''.join(str(s) for s in r[i])
        return result

    def get_board(self, n, row, result, board):
        if row >= n:
            result.append(board)
            return
        for column in range(n):
            if board[row][column] == 0:
                board, temp_board = self.new_board(n, row, column, board)
                self.get_board(n, row+1, result, board)
                board = temp_board.copy()

    def new_board(self, n, x, y, board):
        temp_board = copy.deepcopy(board)
        # 方向数组,对于8个方向
        board[x][y] = 'Q'
        dx = [0, 0, -1, 1, -1, 1, -1, 1] # 上 下 左 右 左上 右上 左下 右下
        dy = [-1, 1, 0, 0, -1, -1, 1, 1] # 上 下 左 右 左上 右上 左下 右下
        for i in range(8):
            for j in range(1, n):
                new_x = x + dx[i] * j
                new_y = y + dy[i] * j
                if (new_x >= 0 and new_x < n) and (new_y >= 0 and new_y < n):
                    board[new_x][new_y] = '.'
        return board, temp_board

Reference:

class Solution:
    def solveNQueens(self, n):
        def DFS(queens, xy_dif, xy_sum):
            p = len(queens)
            if p==n:
                result.append(queens)
                return None
            for q in range(n):
                if q not in queens and p-q not in xy_dif and p+q not in xy_sum: 
                    DFS(queens+[q], xy_dif+[p-q], xy_sum+[p+q])  
        result = []
        DFS([],[],[])
        return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result]

你可能感兴趣的:(Leetcode-51N-Queens)