스도쿠 검사

이세진·2022년 4월 15일
0

코테준비

목록 보기
20/87

생성일: 2022년 1월 14일 오후 4:57

구현 코드

# 스도쿠 검사
import sys
sys.stdin = open("input.txt", "rt")
sudoku = [list(map(int, input().split())) for _ in range(9)]
isSudoku = True
s1 = set()
s2 = set()
s3 = set()
s4 = set()
s5 = set()
s6 = set()
s7 = set()
s8 = set()
s9 = set()

for i in range(9):
    set1 = set(sudoku[0])
    if len(set1) != 9:
        isSudoku = False
    set2 = set()
    for j in range(9):
        set2.add(sudoku[j][i])
        if i < 3 and j < 3:
            s1.add(sudoku[i][j])
        elif i < 3 and j >= 3 and j < 6:
            s2.add(sudoku[i][j])
        elif i < 3 and j >= 6 and j < 9:
            s3.add(sudoku[i][j])
        elif i >= 3 and i < 6 and j < 3:
            s4.add(sudoku[i][j])
        elif i >= 3 and i < 6 and j >= 3 and j < 6:
            s5.add(sudoku[i][j])
        elif i >= 3 and i < 6 and j >= 6 and j < 9:
            s6.add(sudoku[i][j])
        elif i >= 6 and i < 9 and j < 3:
            s7.add(sudoku[i][j])
        elif i >= 6 and i < 9 and j >= 3 and j < 6:
            s8.add(sudoku[i][j])
        else:
            s9.add(sudoku[i][j])
    if len(set2) != 9:
        isSudoku = False

if len(s1) == len(s2) == len(s3) == len(s4) ==len(s5) ==len(s6) ==len(s7) ==len(s8) ==len(s9) == 9:
    pass
else:
    isSudoku = False

if isSudoku:
    print("YES")
else:
    print("NO")

모범 답안

import sys
sys.stdin=open("input.txt", "r")
def check(a):
    for i in range(9):
        ch1=[0]*10
        ch2=[0]*10
        for j in range(9):
            ch1[a[i][j]]=1
            ch2[a[j][i]]=1
        if sum(ch1)!=9 or sum(ch2)!=9:
            return False
    for i in range(3):
        for j in range(3):
            ch3=[0]*10
            for k in range(3):
                for s in range(3):
                    ch3[a[i*3+k][j*3+s]]=1
            if sum(ch3)!=9:
                return False
    return True

a=[list(map(int, input().split())) for _ in range(9)]
if check(a):
    print("YES")
else:
    print("NO")

차이점

  • 내가 구현한 코드에서는 9 x 9 스도쿠 판에서 3 x 3 사이즈의 작은 구역을 이중 for문 속에서 조건문을 걸어서 확인하였다.
  • 모범 답안에서는 4 중 for 문을 사용하여 조건문의 수를 줄이는 방식으로 3 x 3 사이즈의 구역을 검사하였다.
profile
나중은 결코 오지 않는다.

0개의 댓글