https://www.acmicpc.net/problem/1976
๋ณดํต ํ์ด ๊ฒ์ํด๋ณด๋ฉด ์ ๋์จํ์ธ๋๋ก ๋ง์ด ํ์๋๋ฐ ๋๋ BFS๋ก ํ์๋ค
์ฌํ ๊ณํ์ด 1 2 3 ์ผ ๋ 1โ2, 2โ3์ผ๋ก ๊ฐ ์ ์๋์ง ๊ฐ๊ฐ BFS๋ก ํ์ธํ๋ ๋ฐฉ์์ผ๋ก ํ์์
์ฆ, m-1๋ฒ BFS๋ก ํ์ํ๋ค
from collections import deque
n = int(input())
m = int(input())
city = []
for i in range(n):
city.append(list(map(int, input().split())))
plan = list(map(int, input().split()))
def bfs(s, e):
q = deque()
q.append(s)
visited = [False] * n
visited[s] = True
while q:
here = q.popleft()
if here == e:
return True
for i in range(n):
if city[here][i] == 1 and not visited[i]:
visited[i] = True
q.append(i)
return False
answer = True
for i in range(m-1):
if plan[i] != plan[i+1]:
if not bfs(plan[i]-1, plan[i+1]-1):
answer = False
break
if answer:
print('YES')
else:
print('NO')
์ฌ์ค BFS ํจ์์์ city[here][i]๋ก ์จ์ผํ๋๋ฐ city[v][i]๋ก ์๋ชป ์จ์ 1์๊ฐ ์ฝ์งํ๊ธฐ ๋๋ฌธ์ ์ต์ธํด์ ์ฐ๋ ๊ฒ์๊ธ๐