파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 6. 4. 23:45

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

 

N-Queens - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

N-Queens 문제는 좀 어려운 듯..
다른 사람의 해설을 보고 풀긴 했는데, 1차원 형태로 바꿔서 푸는 듯..?
오늘은 시간이 없어서 소스 풀이도 제대로 못했네 ㅠ

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        column = [0] * n
        diag1, diag2 = [0] * (2 * n - 1), [0] * (2 * n - 1)
        res = []
        
        def boardState():
            rows = []
            for y in column:
                rows.append(((y-1) * '.') + 'Q' + ((n - y) * '.'))
            return rows
        
        def search(y):
            if y == n:
                res.append(boardState())
                return
            for x in range(n):
                if column[x] or diag1[x+y] or diag2[x-y+n-1]:
                    continue
                column[x] = diag1[x+y] = diag2[x-y+n-1] = y+1
                search(y+1)
                column[x] = diag1[x+y] = diag2[x-y+n-1] = 0
        search(0)
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.06.06
Today's Challenge  (0) 2022.06.05
Today's Challenge  (0) 2022.06.03
Today's Challenge  (0) 2022.06.02
Today's Challenge  (0) 2022.06.01
Comments