Skip to content

Commit 35025db

Browse files
committed
[BOJ] #14940. 쉬운 최단거리 / 실버1 / 33분 / 실패
1 parent ba593ee commit 35025db

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
# 목표지점까지의 거리 구하기
6+
def find_distance_to_goal(n, m, grid):
7+
# 거리배열(모든 지점에 대한 거리를 저장)
8+
distances = [[-1 for _ in range(m)] for _ in range(n)]
9+
10+
# 목표지점 찾기
11+
for i in range(n):
12+
for j in range(m):
13+
if grid[i][j] == 2: # 목표지점의 위치 저장하고, 0으로 설정
14+
target_x = i
15+
target_y = j
16+
distances[i][j] = 0
17+
if grid[i][j] == 0: # 땅이 아닌 곳이므로 0으로 설정
18+
distances[i][j] = 0
19+
20+
queue = deque([(target_x, target_y)]) # 큐 초기화
21+
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 방향 리스트
22+
23+
# BFS 탐색
24+
while queue:
25+
x, y = queue.popleft() # 현재지점 pop
26+
for dx, dy in directions:
27+
nx, ny = x + dx, y + dy # 현재 지점에서 상하좌우 인접한 지점
28+
# 인접한 지점이 지도의 범위 안에 있고, 갈 수 있는 땅(값이 1)이며, 아직 방문하지 않은 지점이라면:
29+
if (0 <= nx < n and 0 <= ny < m) and grid[nx][ny] == 1 and distances[nx][ny] == -1:
30+
distances[nx][ny] = distances[x][y] + 1 # 인접한 지점의 거리를 현재 지점의 거리 + 1로 설정
31+
queue.append((nx, ny)) # 인접한 지점을 큐에 추가
32+
33+
return distances
34+
35+
# 초기화
36+
n, m = map(int, input().split()) # n: 세로, m: 가로
37+
grid = [] # 지도
38+
for _ in range(n):
39+
line = list(map(int, input().split()))
40+
grid.append(line)
41+
42+
# 함수 호출
43+
distances = find_distance_to_goal(n, m, grid)
44+
45+
# 정답 출력
46+
for d in distances:
47+
print(" ".join(map(str, d))) # 공백을 구분하여 출력

0 commit comments

Comments
 (0)