[๋ฐฑ์ค€ ๐Ÿฅ‡4] 1976๋ฒˆ ์—ฌํ–‰ ๊ฐ€์ž (Python/ํŒŒ์ด์ฌ)

mingssoยท2023๋…„ 3์›” 19์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
20/35

1๏ธโƒฃ ๋ฌธ์ œ

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



2๏ธโƒฃ ์ฝ”๋“œ

๋ณดํ†ต ํ’€์ด ๊ฒ€์ƒ‰ํ•ด๋ณด๋ฉด ์œ ๋‹ˆ์˜จํŒŒ์ธ๋“œ๋กœ ๋งŽ์ด ํ’€์—ˆ๋˜๋ฐ ๋‚˜๋Š” 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์‹œ๊ฐ„ ์‚ฝ์งˆํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์–ต์šธํ•ด์„œ ์“ฐ๋Š” ๊ฒŒ์‹œ๊ธ€๐Ÿ˜”

profile
๐Ÿฅ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ’ฐ

0๊ฐœ์˜ ๋Œ“๊ธ€