알고리즘/백준 문제풀이

[boj] 백준 2045 마방진 python 풀이

감자156 2023. 9. 16. 17:06
반응형

문제

https://www.acmicpc.net/problem/2045

 

2045번: 마방진

3 by 3 크기의 마방진을 생각하자. 마방진이란 가로, 세로, 대각선 위의 수들의 합이 모두 같은 성질을 가지고 있다. 몇 가지 마방진을 예로 들면 다음과 같다. 생일빵을 맞은 정신을 잃은 동주와

www.acmicpc.net

 

 

문제 풀이

지저분하지만 단순 구현..

 

코드

import sys
input = sys.stdin.readline

'''
마방진 : 가로, 세로, 대각선 위의 수들의 합이 모두 같다
주어진 마방진을 가로, 세로, 대각선 조사하여 합이 되는 수를 구함
마방진을 계속 가로, 세로, 대각선으로 탐색하며 0을 지움.
예외 케이스)
0 9 9
9 0 9
9 9 0
'''
MAP = [list(map(int,input().split())) for _ in range(3)]
## 마방진 수의 합 찾기
def find_all(MAP):
    total_list = [MAP[0], MAP[1], MAP[2]] # 가로
    total_list.append([MAP[0][0], MAP[1][0], MAP[2][0]]) # 세로
    total_list.append([MAP[0][1], MAP[1][1], MAP[2][1]]) # 세로
    total_list.append([MAP[0][2], MAP[1][2], MAP[2][2]]) # 세로
    total_list.append([MAP[0][0], MAP[1][1], MAP[2][2]]) # 대각선
    total_list.append([MAP[0][2], MAP[1][1], MAP[2][0]]) # 대각선
    
    SUM = sorted(total_list, key=lambda x:x.count(0))[0]
    if 0 in SUM: # 예외케이스
        return (sum(MAP[0]) + sum(MAP[1]) + sum(MAP[2]))/2
    return sum(SUM)

total = int(find_all(MAP))

## 마방진 채우기 시작
while True:
    for i in range(3):
        if MAP[i].count(0) == 1:
            MAP[i][MAP[i].index(0)] = total - sum(MAP[i])
    rotated_MAP = list(map(list, zip(*MAP[::-1])))
    for i in range(3):
        if rotated_MAP[i].count(0) == 1:
            rotated_MAP[i][rotated_MAP[i].index(0)] = total - sum(rotated_MAP[i])
    MAP = list(map(list, zip(*rotated_MAP)))[::-1]

    for i in range(3):
        if 0 in MAP[i]:
            continue
    else: 
        break

for i in range(3):
    print(*MAP[i])
반응형