๋ฌธ์
ํ์ด
# 1249. [S/W ๋ฌธ์ ํด๊ฒฐ ์์ฉ] 4์ผ์ฐจ - ๋ณด๊ธ๋ก
from collections import deque
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def bfs(x, y):
q = deque([(x,y)])
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < N:
if dist[x][y] + graph[nx][ny] < dist[nx][ny]: // ๋ค์ ๊ฐ์ผํ ๊ฑฐ๋ฆฌ๊ฐ ์ง๊ธ๊น์ง ๊ฑฐ๋ฆฌ + ๊ทธ๋ํ์ ํฌ๊ธฐ ๋ณด๋ค ํฐ ๊ฒฝ์ฐ
dist[nx][ny] = dist[x][y] + graph[nx][ny]
q.append((nx, ny))
for test_case in range(1, int(input())+1):
N = int(input())
graph = [list(map(int, input())) for _ in range(N)]
dist = [[1e9]*N for _ in range(N)]
dist[0][0] = graph[0][0]
bfs(0,0)
print("#{} {}".format(test_case, dist[N-1][N-1]))
BFS์ ๋ค์ต์คํธ๋ผ ๋ฑ์ ์ด์ฉํด์ ํธ๋ ์ฌ๋ฌ๊ฐ์ง ๋ฐฉ๋ฒ์ด ์กด์ฌํ๋ค. ๋๋ BFS๊ฐ ๊ฐ์ฅ ํธํ ๋ฐฉ๋ฒ์ด์ด์ ์ฌ์ฉํ๋ค.
'๐๏ธ Algorithm > โน๏ธ SW Expert Academy [SWEA]' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
โน๏ธ[SW Expert Academy] [Python] [D3] [1244] ์ต๋ ์๊ธ (1) | 2024.03.18 |
---|---|
โน๏ธ[SW Expert Academy] [Python] [D4] [1210] Ladder1 (0) | 2024.03.15 |
โน๏ธ[SW Expert Academy] [Python] [D2] [1859] ๋ฐฑ๋ง ์ฅ์ ํ๋ก์ ํธ (0) | 2024.03.13 |
โน๏ธ[SW Expert Academy] [Python] [D3] [1208] Flatten (0) | 2024.03.12 |
โน๏ธ [SW Expert Academy] [Python] [D3] 1206. View (0) | 2024.03.12 |