[๋ฐฑ์ค] 16928 ๋ฑ๊ณผ ์ฌ๋ค๋ฆฌ ๊ฒ์ (python ํ์ด์ฌ)
https://www.acmicpc.net/problem/16928
16928๋ฒ: ๋ฑ๊ณผ ์ฌ๋ค๋ฆฌ ๊ฒ์
์ฒซ์งธ ์ค์ ๊ฒ์ํ์ ์๋ ์ฌ๋ค๋ฆฌ์ ์ N(1 ≤ N ≤ 15)๊ณผ ๋ฑ์ ์ M(1 ≤ M ≤ 15)์ด ์ฃผ์ด์ง๋ค. ๋์งธ ์ค๋ถํฐ N๊ฐ์ ์ค์๋ ์ฌ๋ค๋ฆฌ์ ์ ๋ณด๋ฅผ ์๋ฏธํ๋ x, y (x < y)๊ฐ ์ฃผ์ด์ง๋ค. x๋ฒ ์นธ์ ๋์ฐฉํ๋ฉด, y๋ฒ ์นธ์ผ
www.acmicpc.net
์์ด๋์ด
1. bfs
- ์ฃผ์ฌ์๋ฅผ ์ ํ(1 ~ 6)ํ ์ ์๋ ์ ๊ณผ ์ต๋จ ํ์๋ฅผ ๊ตฌํดํ๋ค๋ ์ ์ bfs๋ฅผ ์ ํ
- ๋ฑ๊ณผ ์ฌ๋ค๋ฆฌ๋ง ์ ์ฒดํฌํด์ฃผ๋ฉด ๋๋ ๋ฌธ์ .
์ฝ๋ ์ค๋ช
deq = deque()
deq.append([1, 0])
visited[1] = True
while deq:
po, count = deq.popleft()
if po == 100:
print(count)
break
for i in range(1,7):
newpo = po + i
if newpo > 100:
continue
for k in range(len(sadari)):
if newpo == sadari[k][0] and not visited[newpo]:
visited[newpo] = True
deq.append([sadari[k][1], count + 1])
for j in range(len(baaam)):
if newpo == baaam[j][0] and not visited[newpo]:
visited[newpo] = True
deq.append([baaam[j][1], count + 1])
if not visited[newpo]:
visited[newpo] = True
deq.append([newpo, count + 1])
bfs๋ก ๋ฏธ๋ก ์ฐพ๊ธฐ ํ ๋์ฒ๋ผ ์ํ์ข์ฐ ํ์ ๋์ ์ฃผ์ฌ์ 1 ~ 6์ ํ์ธํด์ฃผ๋ฉด ๋๋ค.
๋จผ์ 100์ ๋์ด๊ฐ๋ฉด ์ ๋๋ฏ๋ก 100์ ๋๊ธฐ๋ฉด continue๋ก ๋๊ฒจ์ค๋ค. ์ดํ ๊ทธ ์นธ์ ๋ฑ์ด๋ ์ฌ๋ค๋ฆฌ๊ฐ ์๋์ง ํ์ธํด์ค๋ค.
์๋ค๋ฉด ๊ทธ๋ฅ ์ด๋ํด์ฃผ๋ฉด ๋๋ค.
ํ์๋์ด๋ํ ์์น์ ํ์๋ฅผ ์ถ๊ฐํด์ฃผ๋ฉด ๋๋ค.
์ต์ข ์ ์ผ๋ก ์์น๊ฐ 100์ด ๋๋ค๋ฉด ํ์๋ฅผ ์ถ๋ ฅํด์ค๋ค.
์ ์ฒด ์ฝ๋
import sys
from collections import deque
def bfs():
deq = deque()
deq.append([1, 0])
visited[1] = True
while deq:
po, count = deq.popleft()
if po == 100:
print(count)
break
for i in range(1,7):
newpo = po + i
if newpo > 100:
continue
for k in range(len(sadari)):
if newpo == sadari[k][0] and not visited[newpo]:
visited[newpo] = True
deq.append([sadari[k][1], count + 1])
for j in range(len(baaam)):
if newpo == baaam[j][0] and not visited[newpo]:
visited[newpo] = True
deq.append([baaam[j][1], count + 1])
if not visited[newpo]:
visited[newpo] = True
deq.append([newpo, count + 1])
if __name__ == '__main__':
N, M = map(int, input().split())
visited = [False for _ in range(101)]
sadari = []
baaam = []
for i in range(N):
sadari.append([int(x) for x in sys.stdin.readline().rstrip().split()])
for i in range(M):
baaam.append([int(x) for x in sys.stdin.readline().rstrip().split()])
bfs()