연결정보를 저장할 리스트(chk)와 이어져있음을 표시해 줄 리스트(visit)를 새롭게 생성한다.
단방향성 그래프이므로 연결 정보를 저장할 때는 입력된 쌍 그대로만을 고려하면 된다.
def dfs(i):
visit[i]=True
for e in chk[i]:
if not visit[e]:
dfs(e)
for tc in range(1,int(input())+1):
V,E = map(int,input().split())
chk=[[] for _ in range(V+1)]
visit =[False]*(V+1)
for i in range(E):
x,y=map(int,input().split())
chk[x].append(y)
start,end = map(int,input().split())
dfs(start)
res=1
if not visit[end]:
res=0
print(f'#{tc} {res}')
텍스트