chyam

[백준] 1976번,python - 여행 가자 본문

백준

[백준] 1976번,python - 여행 가자

chyam_eun 2025. 9. 24. 20:09

https://www.acmicpc.net/problem/1976

from collections import deque
import sys
input = sys.stdin.readline

n = int(input())
m = int(input())
graph = [[] for _ in range(n+1)]


for i in range(n):
    tmp = list(map(int,input().split()))
    for j in range(n):
        if tmp[j] == 1:
            graph[i+1].append(j+1)

travel = list(map(int,input().split()))
visited = [False] * (n+1) # 도시에 방문했는지

def bfs(travel):
    queue = deque([travel[0]])
    visited[travel[0]] = True

    while queue:
        t = queue.popleft()
        for i in graph[t]:
            if not visited[i]: # 방문안한곳 가기 
                queue.append((i))
                visited[i] = True


bfs(travel)

# 여행 계획에 있는 도시들 다 방문했는가
if all(visited[city] for city in travel):
    print("YES")
else:
    print("NO")