Skip to content

Commit 0b55df1

Browse files
committed
[Silver I] Title: 쉬운 최단거리, Time: 212 ms, Memory: 120928 KB -BaekjoonHub
1 parent d07bd4e commit 0b55df1

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# [Silver I] 쉬운 최단거리 - 14940
2+
3+
[문제 링크](https://www.acmicpc.net/problem/14940)
4+
5+
### 성능 요약
6+
7+
메모리: 120928 KB, 시간: 212 ms
8+
9+
### 분류
10+
11+
너비 우선 탐색, 그래프 이론, 그래프 탐색
12+
13+
### 제출 일자
14+
15+
2025년 3월 10일 14:07:12
16+
17+
### 문제 설명
18+
19+
<p>지도가 주어지면 모든 지점에 대해서 목표지점까지의 거리를 구하여라.</p>
20+
21+
<p>문제를 쉽게 만들기 위해 오직 가로와 세로로만 움직일 수 있다고 하자.</p>
22+
23+
### 입력
24+
25+
<p>지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000)</p>
26+
27+
<p>다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이다. 입력에서 2는 단 한개이다.</p>
28+
29+
### 출력
30+
31+
<p>각 지점에서 목표지점까지의 거리를 출력한다. 원래 갈 수 없는 땅인 위치는 0을 출력하고, 원래 갈 수 있는 땅인 부분 중에서 도달할 수 없는 위치는 -1을 출력한다.</p>
32+
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import sys
2+
input = sys.stdin.readline
3+
from collections import deque
4+
5+
def bfs():
6+
q = deque()
7+
8+
for i in range(n):
9+
for j in range(m):
10+
if graph[i][j] == 2:
11+
q.append((i, j))
12+
dist[i][j] = 0
13+
14+
while q:
15+
x, y = q.popleft()
16+
17+
for i in range(4):
18+
nx = x + dx[i]
19+
ny = y + dy[i]
20+
21+
if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1 and dist[nx][ny] == -1:
22+
dist[nx][ny] = dist[x][y] + 1
23+
q.append((nx, ny))
24+
25+
n, m = map(int, input().split())
26+
27+
graph = []
28+
for _ in range(n):
29+
graph.append(list(map(int, input().split())))
30+
31+
dx = [-1, 1, 0, 0]
32+
dy = [0, 0, -1, 1]
33+
34+
dist = [[-1] * m for _ in range(n)]
35+
36+
for i in range(n):
37+
for j in range(m):
38+
if graph[i][j] == 0:
39+
dist[i][j] = 0
40+
41+
bfs()
42+
43+
for row in dist:
44+
print(*row)

0 commit comments

Comments
 (0)