Skip to content

Commit c12e76f

Browse files
committed
[Silver I] Title: 쉬운 최단거리, Time: 1776 ms, Memory: 74136 KB -BaekjoonHub
1 parent 9482893 commit c12e76f

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-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+
메모리: 74136 KB, 시간: 1776 ms
8+
9+
### 분류
10+
11+
너비 우선 탐색, 그래프 이론, 그래프 탐색
12+
13+
### 제출 일자
14+
15+
2024년 11월 25일 13:26:18
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: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
static int N,M, arr[][], visited[][], startN, startM;
7+
static int dx[] = {-1,1,0,0};
8+
static int dy[] = {0,0,-1,1};
9+
public static void main(String[] args) throws IOException {
10+
11+
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
12+
13+
StringTokenizer st = new StringTokenizer(br.readLine());
14+
N = Integer.parseInt(st.nextToken());
15+
M = Integer.parseInt(st.nextToken());
16+
17+
arr = new int[N+1][M+1];
18+
visited = new int[N+1][M+1];
19+
20+
for(int i =1; i<=N; i++) {
21+
st= new StringTokenizer(br.readLine());
22+
for(int j =1; j<=M; j++) {
23+
arr[i][j] = Integer.parseInt(st.nextToken());
24+
if(arr[i][j]==2) {
25+
startN= i;
26+
startM = j;
27+
}
28+
}
29+
}
30+
bfs(startN, startM);
31+
for(int i =1; i<=N; i++) {
32+
for(int j =1; j<=M; j++) {
33+
if(visited[i][j] == 0 && arr[i][j]== 1)
34+
System.out.print(-1 +" ");
35+
else
36+
System.out.print(visited[i][j] +" ");
37+
}
38+
System.out.println();
39+
}
40+
}
41+
42+
static void bfs(int startN, int startM) {
43+
44+
visited[startN][startM] = 0;
45+
46+
Queue<int[]> queue= new LinkedList<>();
47+
queue.add(new int[] { startN, startM});
48+
49+
while(!queue.isEmpty()) {
50+
int now [] = queue.poll();
51+
int nowx = now[0];
52+
int nowy = now[1];
53+
54+
for(int i =0; i<4; i++) {
55+
int nx = nowx + dx[i];
56+
int ny = nowy + dy[i];
57+
58+
if(nx >=1 && nx <=N && ny <=M && ny>=1 && arr[nx][ny] ==1) {
59+
if(visited[nx][ny]== 0 || visited[nx][ny] > visited[nowx][nowy]+1) {
60+
visited[nx][ny] = visited[nowx][nowy] +1;
61+
queue.add(new int[] {nx,ny});
62+
}
63+
}
64+
}
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)