[LeetCode] 36. Valid Sudoku

2023. 8. 18. 10:41·Problem Solving/LeetCode

출처 : https://leetcode.com/problems/valid-sudoku/description/

 

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

 

 

내 풀이 :

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        def checkRow(r) :
            dic = collections.defaultdict(int)
            for a in range(9) :
                if board[r][a] == '.' : continue
                dic[board[r][a]] += 1
                if dic[board[r][a]] >= 2 :
                    return 0
            return 1

        
        def checkCol(c):
            dic = collections.defaultdict(int)
            for a in range(9) :
                if board[a][c] == '.' : continue
                dic[board[a][c]] += 1
                if dic[board[a][c]] >= 2 :
                    return 0
            return 1
        
        def checkGrid(r, c) :
            dir =[[0,1,2],[3,4,5],[6,7,8]]
            r,c = r//3, c//3
            dic = {}
            for x in dir[r] :
                for y in dir[c] :
                    if board[x][y] == '.' : continue
                    if board[x][y] not in dic :
                        dic[board[x][y]] = 0
                        dic[board[x][y]] += 1
                    else :
                        return 0
            return 1

        
        for i in range(len(board)) :
            for j in range(len(board)) :
                if board[i][j] != '.' :
                    if not checkRow(i) or not checkCol(j) or not checkGrid(i,j) :
                        print(i,j)
                        return False
        return True

 

 

다른 사람 풀이 :

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        
        rows = [set() for i in range(9)]
        cols = [set() for i in range(9)]
        mMat = [set() for i in range(9)]
        
        for i in range(9):
            for j in range(9):
                cur = board[i][j]
                if cur != '.':
                    
                    k = (i // 3 ) * 3 + j // 3
                
                    if cur not in rows[i]: rows[i].add(cur)
                    else: return False
                    
                    if cur not in cols[j]: cols[j].add(cur)
                    else: return False
                
                    if cur not in mMat[k]: mMat[k].add(cur)
                    else: return False
        return True

 

나는 무지성으로 함수 구현을 해줬기 때문에 코드가 엄청 길다...... 하지만 set()으로 각 miniMatrix, row,  col을 관리해줌으로서 코드 가독성도 높히고 짧게 구현할 수 있었던 것..! 여기서 한 가지 짚고 넘어가야할 점이 있다면 k이다. miniMatrix를 위한 변수이다. 다시 말해서, 9 * 9 격자에서 각 miniMatrix를 3 * 3으로 나눠서 생각했을 때, i와 j 값에 따라 해당 좌표가 속하는 위치를 구할 수 있다.

k = (i // 3) * 3 + j // 3

ex) i = 4  j = 7

 

(4 // 3) * 3 + 7 // 3 = 1 * 3 + 2 = 3 + 2 = 5

 

아래와 같이 i,j좌표가 속한 miniMatrix의 위치를 알 수 있다.

'Problem Solving/LeetCode' 카테고리의 다른 글
  • [LeetCode] 198. House Robber
  • [LeetCode] 238. Product of Array Except Self
  • [LeetCode] 347. Top K Frequent Elements
  • [LeetCode] 746. Min Cost Climbing Stairs
kimdozzi
kimdozzi
끝까지 포기하지 않으면, 내가 다 이겨!
  • kimdozzi
    도브로
    kimdozzi
  • 전체
    오늘
    어제
    • 분류 전체보기 (132)
      • Problem Solving (49)
        • Baekjoon (29)
        • Programmers (0)
        • LeetCode (17)
        • 삼성 유형 (2)
      • Computer Science (27)
        • Operating System (2)
        • Algorithms (13)
        • Network (6)
        • DataBase (6)
      • Backend (33)
        • JavaScript (0)
        • TypeScript (6)
        • Java (7)
        • Spring Boot (7)
        • Spring Security (6)
        • JPA (2)
        • Mybatis (1)
        • Junit5 (1)
        • Redis (3)
      • DevOps (14)
        • Git, Github (5)
        • docker (4)
        • AWS (3)
        • nginx (2)
      • etc (6)
        • IntelliJ (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 티스토리
    • 설정
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    인터페이스
    AWS
    구간 업데이트
    오프라인 쿼리
    삼성기출
    인덱스 시그니처
    알고리즘
    컨테이너
    interface
    TypeScript
    CORS
    티스토리챌린지
    python
    파이썬
    백준
    오블완
    S3
    segment tree
    세그먼트 트리
    PrefixSum
    구간합
    인덱서블 타입
    점 업데이트
    온라인 쿼리
    docker image
    imos법
    Bucket
    타입스크립트
    도커
    누적합
    docker
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
kimdozzi
[LeetCode] 36. Valid Sudoku
상단으로

티스토리툴바