https://www.acmicpc.net/problem/7562
7562๋ฒ: ๋์ดํธ์ ์ด๋
์ฒด์คํ ์์ ํ ๋์ดํธ๊ฐ ๋์ฌ์ ธ ์๋ค. ๋์ดํธ๊ฐ ํ ๋ฒ์ ์ด๋ํ ์ ์๋ ์นธ์ ์๋ ๊ทธ๋ฆผ์ ๋์์๋ค. ๋์ดํธ๊ฐ ์ด๋ํ๋ ค๊ณ ํ๋ ์นธ์ด ์ฃผ์ด์ง๋ค. ๋์ดํธ๋ ๋ช ๋ฒ ์์ง์ด๋ฉด ์ด ์นธ์ผ๋ก ์ด๋ํ ์
www.acmicpc.net
from collections import deque
def bfs(y,x,m):
global Max
q = deque()
q.append((y,x,m))
#๋ฐฉ๋ฌธ ์ฒดํฌ๋ฅผ ์ํ visit๋ฐฐ์ด
visit=[[0]*n for _ in range(n)]
visit[y][x] = 1
while q:
ny,nx,nm = q.popleft()
#์์ง์ ๊ฐฑ์ ํด ์ต๋จ๊ฒฝ๋ก ์ฐพ๊ธฐ
if Max<nm:
Max=nm
#๋์ฐฉํ๋ฉด while๋ฌธ ์ข
๋ฃ
if ny==ey and nx == ex:
break
#๋์ดํธ์ ์์ง์
directy=[-1,-2,-2,-1,1,2,2,1]
directx=[-2,-1,1,2,2,1,-1,-2]
for i in range(8):
dy = directy[i] + ny
dx = directx[i] + nx
if 0<=dy<n and 0<=dx<n:
if visit[dy][dx] ==0:
visit[dy][dx]=nm
q.append((dy,dx,nm+1))
t = int(input())
for tc in range(t):
n = int(input())
sy,sx = map(int,input().split())
ey,ex = map(int,input().split())
Max=0
bfs(sy,sx,0)
print(Max)
๐์ต์ ์ด๋ ํ์๋ฅผ ์ฐพ์์ผํ๊ธฐ ๋๋ฌธ์ BFS๋ฅผ ์ด์ฉํด์ ํ์๋ค.
๐์์์ ์ ์ ๋ ฅ๋ฐ์ bfs ํจ์์ ๋ฃ์ด์ฃผ๋๋ฐ ์ด๋ movement(0)๋ ๊ฐ์ด ๋ฃ์ด์ค๋ค!
๐deque๋ฅผ ์ฌ์ฉํด ์๊ฐ์ ์ค์.
๐๋์ดํธ์ ์ต๋ ์ด๋ ๊ฒฝ๋ก๊ฐ ๋ฌธ์ ์์ ๊ทธ๋ฆผ์ผ๋ก ์ฃผ์ด์ ธ ์๋๋ฐ ์์ ์์ directy,directx์ ํํ๋์ด ์๋ค.
๐๋์ฐฉ์ ์ ๋์ฐฉํ๋ฉด while๋ฌธ ์ข ๋ฃ
๐์ ํ์ ์ธ bfsํ์ ๋ง์ถฐ ์ฝ๋๋ฅผ ์ง๋ฉด ์ฝ๊ฒ ํด๊ฒฐ๋๋ ๋ฌธ์
'Problem Solving > BAEKJOON' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[baekjoon]python #11055 ๊ฐ์ฅ ํฐ ์ฆ๊ฐ ๋ถ๋ถ ์์ด (0) | 2022.05.20 |
---|---|
[baekjoon]python #11053 ๊ฐ์ฅ ๊ธด ์ฆ๊ฐํ๋ ๋ถ๋ถ ์์ด (0) | 2022.05.20 |
[baekjoon]python #14494 ๋ค์ด๋๋ฏน์ด ๋ญ์์? (0) | 2022.05.18 |
[baekjoon]python #14606 ํผ์ (Small) (0) | 2022.05.18 |
[baekjoon]python #1946 ์ ์ ์ฌ์ (0) | 2022.05.13 |
๋๊ธ