ν‹°μŠ€ν† λ¦¬ λ·°

728x90
λ°˜μ‘ν˜•

문제

 

2580번: μŠ€λ„μΏ 

μŠ€λ„μΏ λŠ” 18μ„ΈκΈ° μŠ€μœ„μŠ€ μˆ˜ν•™μžκ°€ λ§Œλ“  '라틴 μ‚¬κ°ν˜•'μ΄λž‘ νΌμ¦μ—μ„œ μœ λž˜ν•œ κ²ƒμœΌλ‘œ ν˜„μž¬ λ§Žμ€ 인기λ₯Ό λˆ„λ¦¬κ³  μžˆλ‹€. 이 κ²Œμž„μ€ μ•„λž˜ κ·Έλ¦Όκ³Ό 같이 κ°€λ‘œ, μ„Έλ‘œ 각각 9κ°œμ”© 총 81개의 μž‘μ€ 칸으둜 이루

www.acmicpc.net

 

문제 풀이

 κ°€λ‘œ, μ„Έλ‘œμ™€ 3 X 3 μ˜μ—­μ„ ν™•μΈν•˜μ—¬ μŠ€λ„μΏ  퍼즐에 μ±„μ›Œμ§€μ§€ μ•Šμ€ 숫자 쀑 μ•Œλ§žμ€ 숫자λ₯Ό μ±„μš°λŠ” λ¬Έμ œμ΄λ‹€. μ±„μ›Œμ§€μ§€ μ•ŠλŠ” 곳은 0으둜 μ œμ‹œλœλ‹€. λ”°λΌμ„œ 0인 λΆ€λΆ„μ˜ μ’Œν‘œλ₯Ό μ°Ύκ³  ν•΄λ‹Ή μ’Œν‘œμ— μ–΄λ–€ 값을 λŒ€μž…ν•˜λ©΄ λ˜λŠ”μ§€ ν™•μΈν•˜λ©΄ λœλ‹€. ν™•μΈν•˜λŠ” 방법은 λ‹€μŒκ³Ό κ°™λ‹€.

 

  • ν•œ 행에 μ–΄λ–€ 값이 μ—†λŠ”μ§€ ν™•μΈν•œλ‹€.
  • ν•œ 열에 μ–΄λ–€ 값이 μ—†λŠ”μ§€ ν™•μΈν•œλ‹€.
    • κ·Έλž˜ν”„μ˜ ν–‰/열을 μ „ν™˜μ‹œμΌœ ν™•μΈν•˜λ©΄ 쉽닀.
  • 3 X 3 μ˜μ—­μ— μ–΄λ–€ 값이 μ—†λŠ”μ§€ ν™•μΈν•œλ‹€.

 

μ½”λ“œ

from sys import stdin, exit

# 3 X 3 μ˜μ—­ 확인
def area_check(area, num):
    x, y = map(lambda n: n // 3 * 3, area)
    for i in range(3):
        for j in range(3):
            if num == x_graph[x + i][y + j]:
                return False
    return True


def dfs(cur_find):
    if cur_find == len(zeros):
        for nums in x_graph:
            print(*nums)
        exit(0)

    for num in range(1, 10):
        next_x, next_y = zeros[cur_find]
        if row(next_x, num) and column(next_y, num) \
                and area_check([next_x, next_y], num):
            x_graph[next_x][next_y] = y_graph[next_y][next_x] = num
            dfs(cur_find + 1)
            x_graph[next_x][next_y] = y_graph[next_y][next_x] = 0


if __name__ == '__main__':
    x_graph = [list(map(int, stdin.readline().split())) for _ in range(9)]
    # ν–‰/λ ¬ μ „ν™˜
    y_graph = list(map(list, zip(*x_graph)))
    zeros = [(i, j) for i in range(9) for j in range(9) if not x_graph[i][j]]
    # 행에 값이 μžˆλŠ”κ°€?
    row = lambda x, num: num not in x_graph[x]
    # 열에 값이 μžˆλŠ”κ°€?
    column = lambda y, num: num not in y_graph[y]
    dfs(0)

 ν–‰/열을 ν™•μΈν•˜λŠ” 뢀뢄을 lamda둜 μž‘μ„±ν•˜μ˜€κ³ , lamda둜 μ‰½κ²Œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ 기쑴의 κ·Έλž˜ν”„μ˜ ν–‰/렬을 λ°˜μ „μ‹œμΌ°λ‹€. μ„ νƒλœ 값을 μ²΄ν¬ν•˜κ³  ν•΄μ œν•  λ•Œ, x_graph, y_graph λͺ¨λ‘ 진행해주어야 λœλ‹€.

728x90
λ°˜μ‘ν˜•
λŒ“κΈ€
κΈ€ 보관함
μ΅œκ·Όμ— 올라온 κΈ€
μ΅œκ·Όμ— 달린 λŒ“κΈ€