넘치게 채우기

[LeetCode] 36. Valid Sudoku 본문

PS/LeetCode

[LeetCode] 36. Valid Sudoku

riveroverflow 2023. 8. 28. 16:20
728x90
반응형

https://leetcode.com/problems/valid-sudoku/description/?envType=study-plan-v2&envId=top-interview-150 

 

Valid Sudoku - LeetCode

Can you solve this real interview question? Valid Sudoku - Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: 1. Each row must contain the digits 1-9 without repetition. 2. Each c

leetcode.com

문제 유형 : 2차원배열

문제 난이도 : Medium

 

문제

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

 

풀이

9 * 9 2차원배열을 순회하는 중첩 반복문을 만든다.

만약 현재의 값이 공백('.')이 아니라면, 리스트에 (i, 현재 값) (현재값, j), (i // 3, j // 3, 현재값)을 추가한다.

i와 j는 각각의 행과 열 값이다.

 

순회가 모두 끝나면 리스트와 중복을 제거한 리스트의 크기를 비교하여 크기가 같으면(중복이 없으면) true를 반환하면 된다.

 

코드

Python3

class Solution:
    def isValidSudoku(self, board):
        table = []
        for i in range(9):
            for j in range(9):
                num = board[i][j]
                if element != '.':
                    table += [(i, num), (num, j), (i // 3, j // 3, num)]
        return len(table) == len(set(table))
 
 
728x90
반응형