SWEA

SWEA 5105. 미로의 거리 [Python]

Hoo_Dev 2022. 3. 24. 23:24

문제 링크 - https://swexpertacademy.com/main/learn/course/lectureProblemViewer.do

def start():
    for i in range(N):
        for j in range(N):
            if arr[i][j] == '2':
                return i, j
    else:
        return -1 -1

def bfs(y, x):
    queue = []
    queue.append((y, x))
    visited[y][x] = 1
    while queue:
        cy, cx = queue.pop(0)
        if arr[cy][cx] == '3':
            return visited[cy][cx] - 2
        for dy, dx in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ny, nx = cy + dy, cx + dx
            if 0 <= ny < N and 0 <= nx < N and arr[ny][nx] != '1' and visited[ny][nx] == 0:
                visited[ny][nx] = visited[cy][cx] + 1
                queue.append((ny, nx))
    return 0


T = int(input())
for tc in range(1, T+1):
    N = int(input())
    arr = [list(input()) for _ in range(N)]
    visited = [[0] * N for _ in range(N)]
    si, sj = start()
    print('#{} {}'.format(tc, bfs(si, sj)))

bfs를 이용한 문제.
시작지점과 도착지점을 포함하기 때문에 최종결과는 도착지점 방문값 -2