https://www.acmicpc.net/problem/16928
์์ด๋์ด
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()
'๐งฉ Problem Solving > [๋ฐฑ์ค]' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2293 ๋์ 1 (python ํ์ด์ฌ) (1) | 2022.07.05 |
---|---|
[๋ฐฑ์ค] 2096 ๋ด๋ ค๊ฐ๊ธฐ (python ํ์ด์ฌ) (0) | 2022.07.04 |
[๋ฐฑ์ค] 5525 IOIOI (python ํ์ด์ฌ) (0) | 2022.07.03 |
[๋ฐฑ์ค] 9375 ํจ์ ์ ์ ํด๋น (python ํ์ด์ฌ) (0) | 2022.06.29 |
[๋ฐฑ์ค] 1074 Z (python ํ์ด์ฌ) (0) | 2022.06.26 |