๐๋ฌธ์
https://www.acmicpc.net/problem/14940
๐์ด๋ค ์๊ณ ๋ฆฌ์ฆ?
1. 2์ฐจ์ ๋ฐฐ์ด์์ ์ต๋จ๊ฑฐ๋ฆฌ -> bfs ๋ฐ๋ก ๋ ์ฌ๋ ค์ผ ๋๋ค!
๐ป์ฝ๋
# 14940 ์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ
from collections import deque
# 2. ๋ชฉํ ์ง์ ์ขํ ์ฐพ๋ ํจ์ ๊ตฌํ
def Search():
for i in range(n):
for j in range(m):
if graph[i][j] == 2:
# 3. ํ์
Bfs(i,j)
return
# 3. bfs ํ์ ํจ์ ๊ตฌํ
def Bfs(x,y):
deq = deque()
deq.append([x,y])
graph[x][y] = 0
visit[x][y] = True
dx = [0,0,-1,1]
dy = [1,-1,0,0]
while deq:
x,y = deq.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx > (n-1) or ny < 0 or ny > (m-1):
continue
if graph[nx][ny] == 1 and visit[nx][ny] == False:
graph[nx][ny] = graph[x][y] + 1
visit[nx][ny] = True
deq.append([nx,ny])
# ๋๋ฌํ ์ ์๋ ์์น -1๋ก
for i in range(n):
for j in range(m):
if graph[i][j] == 1 and visit[i][j] == False:
graph[i][j] = -1
# 1. ์
๋ ฅ ๋ฐ๊ธฐ
# n: ๊ฐ๋ก(ํ,x), m: ์ธ๋ก(์ด,y)
n,m = map(int,input().split())
graph = []
visit = [[False for j in range(m)] for i in range(n)]
for i in range(n):
graph.append(list(map(int,input().split())))
# 2. ๋ชฉํ ์ง์ ์ขํ์ฐพ๊ธฐ
Search()
# 4. ์ถ๋ ฅ
for i in range(n):
print(*graph[i])
๐์ฝ๋ ์ค๋ช
1. ์ ๋ ฅ ๋ฐ๊ธฐ
2. ๋ชฉํ ์ง์ ์ขํ ์ฐพ๊ธฐ
1) ์ฌ๊ธฐ์ ์ค์ํ ๊ฒ์ 2์ ์ขํ๋ฅผ ์ฐพ์์ bfs()๋ฅผ ๋๋ฆฐ ํ ํจ์๋ฅผ ํ์ถํด์ผ๋๋ค. ์๊ทธ๋ฌ๋ฉด bfs๋๋ ค์ ๋ฐ๊ฟ๋์ graph์์ 2๊ฐ ์ถํ์ ๋์ค๋ฉด ๊ทธ ์ขํ๋ก ๋ ๋ค์ bfs๋ฅผ ๋๋ ค๋ฒ๋ฆฐ๋ค.
3. bfs ํ์ ํจ์ ๊ตฌํ
1) ์ด์ ๋ ๋๋ฌด ์ฌ์ด bfs ์ฝ๋ ์ง๊ธฐ
2) ํ, ๊ทธ๋ํ ๋ฒ์ด๋์ง ์๊ฒ ์ค์ ํ๊ธฐ, ๋ฐฉ๋ฌธ์กฐ๊ฑด๋ง ์ ๊ฒฝ ์จ์ฃผ๋ฉด ๋๋ค.
'Algorithm > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 14940 ์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ(ํ์ด์ฌ/python) (0) | 2023.08.17 |
---|---|
[๋ฐฑ์ค] 16985 Maaaaaaaaaze(ํ์ด์ฌ/python) (0) | 2023.08.16 |
[๋ฐฑ์ค] 2194 ์ ๋ ์ด๋์ํค๊ธฐ (ํ์ด์ฌ/python) bfs (0) | 2023.08.14 |
[๋ฐฑ์ค] 1463 1๋ก ๋ง๋ค๊ธฐ (ํ์ด์ฌ/python) dp, bfs (0) | 2023.08.03 |
[๋ฐฑ์ค] 7576 ํ ๋งํ (ํ์ด์ฌ/python) (0) | 2023.08.02 |