로직과의 사투/Algorithm

백준 알고리즘 4485번 녹색 옷 입은 애가 젤다지? - 파이썬

www.acmicpc.net/problem/4485

 

4485번: 녹색 옷 입은 애가 젤다지?

젤다의 전설 게임에서 화폐의 단위는 루피(rupee)다. 그런데 간혹 '도둑루피'라 불리는 검정색 루피도 존재하는데, 이걸 획득하면 오히려 소지한 루피가 감소하게 된다! 젤다의 전설 시리즈의 주

www.acmicpc.net

BFS로 해결할 수 있는 문제였다. 다만 아직 BFS에 대한 이해도가 떨어지다 보니 쉬운 문제임에도 불구하고 생각보다 많은 시간이 걸렸다. BFS 복습을 계속 해야할 것 같다.

 

from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]


def bfs(i, j, graph, costs):
    queue = deque()
    queue.append((i, j))
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < n:
                if costs[nx][ny] > costs[x][y] + graph[nx][ny]:
                    costs[nx][ny] = costs[x][y] + graph[nx][ny]
                    queue.append((nx, ny))


count = 1
while True:
    n = int(input())
    if n == 0:
        break
    graph = []
    costs = [[int(1e9)] * n for _ in range(n)]
    for _ in range(n):
        graph.append(list(map(int, input().split())))

    costs[0][0] = graph[0][0]
    bfs(0, 0, graph, costs)
    print(f'Problem {count}: {costs[n - 1][n - 1]}')
    count += 1