Scribbling

LeetCode: 51. N-Queens 본문

Computer Science/Coding Test

LeetCode: 51. N-Queens

focalpoint 2021. 9. 14. 22:40

오늘도 무지성 스텍 쌓아버린 나의 코드

from copy import deepcopy

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        ret = []
        board = [['.'] * n for _ in range(n)]
        self.solver(n, board, 0, ret)
        return ret
        
    def solver(self, n, board, num_Q, ret):
        if num_Q == n:
            ret_board = []
            for i in range(n):
                temp = list(board[i])
                for j in range(len(temp)):
                    if temp[j] != 'Q':
                        temp[j] = '.'
                ret_board.append(''.join(temp))
            ret.append(ret_board)
            return
        for i in range(n):
            if board[num_Q][i] == '.':
                next_board = deepcopy(board)
                self.place_Q(n, next_board, num_Q, i)
                self.solver(n, next_board, num_Q+1, ret)
                
    def place_Q(self, n, board, y, x):
        i, j = y, x
        while i <= n - 1:
            board[i][j] = '-'
            i += 1
        i, j = y, x
        while i <= n - 1 and j >= 0:
            board[i][j] = '-'
            i += 1
            j -= 1
        i, j = y, x
        while i <= n - 1 and j <= n - 1:
            board[i][j] = '-'
            i += 1
            j += 1
        board[y][x] = 'Q'

 

 

훨씬 좋은 해법

https://leetcode.com/problems/n-queens/discuss/19810/Fast-short-and-easy-to-understand-python-solution-11-lines-76ms

코드에 대한 누군가의 설명

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 55. Jump Game  (0) 2021.09.15
LeetCode: 52. N-Queens II  (0) 2021.09.15
LeetCode: 10. Regular Expression Matching  (0) 2021.09.14
LeetCode: 43. Multiply Strings  (0) 2021.09.13
LeetCode: 45. Jump Game II  (0) 2021.09.13