인프런 커뮤니티 질문&답변
ch 리스트의 필요성
작성
·
223
0
어차피 dis 리스트도 0으로 초기화해서 사용하고 이동할 때마다 해당 인덱스에 jump 횟수를 기록하는데 dis로 중복 여부를 체크하지 않고 굳이 ch를 하나 또 만드는 이유는 무엇인가요?
import sys
from collections import deque
def BFS(n, m):
dQ = deque()
dQ.append(n)
stop = False
while dQ:
now = dQ.popleft()
for next in (now-1, now+1, now+5):
if 0 <= next <= MAX:
if dis[next]==0:
dQ.append(next)
# ch[next] = 1
dis[next] = dis[now]+1
if next == m:
stop = True
break
if stop:
break
print(dis[m])
if __name__=="__main__"
n, m = map(int, sys.stdin.readline().split())
MAX = 10000
dis = [0] * (MAX+1)
BFS(n, m)답변 1
0
김태원
지식공유자
안녕하세요^^
원래 하던대로 아무생각없이 한거죠ㅠㅠ
아래 사과나무에서 상태트리의 레벨값을 배웁니다. 레벨을 거리라 생각하고 아래코드처럼 송아지찾기를 해도 좋습니다.
import sys
from collections import deque
#sys.stdin=open("in1.txt", "r")
MAX = 10000
ch = [0] * (MAX+1)
n,m = map(int,input().split())
ch[n] = 1
dQ = deque()
dQ.append(n)
L=0
flag=1
while dQ and flag==1:
size=len(dQ)
for i in range(size):
if(flag==0):
break
now = dQ.popleft()
for next in (now-1, now+1, now+5):
if(next==m):
print(L+1)
flag=0
break
if 0 <= next <= MAX:
if ch[next]==0:
dQ.append(next)
ch[next] = 1
L+=1





