백준 / 16928 / 뱀과 사다리 (bfs)

맹민재·2023년 4월 13일
0

알고리즘

목록 보기
69/134
from collections import deque

n, m = [int(v) for v in input().split()]
graph = {}
maps = [0] * 101
for i in range(n+m):
    s, e = [int(v) for v in input().split()]
    graph[s] = e

q= deque([[1, 0]])

while q:
    x, deph = q.popleft()
    if x == 100:
        print(deph)
        break
    maps[x] = deph
    for i in range(x+1, x+7):
        if i in graph:
            if not maps[graph[i]]:
                maps[graph[i]] = deph+1
                q.append([graph[i], deph+1])
        elif i < 101:
            if not maps[i]:
                maps[i] = deph+1
                q.append([i, deph+1])

이 문제는 처음 좌표에서 주사위에 대한 for 문 현재 좌표에서 + 1~6 좌표를 돌면서 만약 사다리나 뱀에 해당하는 좌표를 만나면 이동하고 그렇지 않으면 q에 append 하는 것이다.
여기서 중요한 것은 그렇지 않으면 q에 넣는 것이다.

		if i in graph:
            if not maps[graph[i]]:
                maps[graph[i]] = deph+1
                q.append([graph[i], deph+1])
        elif i < 101:
            if not maps[i]:
                maps[i] = deph+1
                q.append([i, deph+1])
		if i in graph:
            if not maps[graph[i]]:
                maps[graph[i]] = deph+1
                q.append([graph[i], deph+1])
        if i < 101:
            if not maps[i]:
                maps[i] = deph+1
                q.append([i, deph+1])

처음에 코드를 윗 부분을 아래 코드로 짰었는데 계속해서 22%에서 오류가 났었다.

if elif로 작성했을 때의 예제 2번의 maps

if if로 작성했을 때의 예제 2번의 maps

생각해보면 사다리나 뱀을 만난 경우는 해당 좌표를 방문하는게 아니라 사다리나 뱀을 지난 후에 도달한 좌표에 방문하는 것이다. 따라서 if if문은 사다리나 뱀을 지난 후 좌표도 큐에 넣고 지나기 전 좌표도 큐에 넣는 것이므로 틀린 코드이다.


코드를 수정해가면서 겨우 겨우 if elif 로 되어야 하는걸 찾았다.

profile
ㄱH ㅂrㄹ ㅈr

0개의 댓글