-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ_2178.java
More file actions
79 lines (63 loc) · 2.06 KB
/
BOJ_2178.java
File metadata and controls
79 lines (63 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.*;
import java.util.*;
public class BOJ_2178 {
static int result;
static int[][] arr;
static int N;
static int M;
static Deque<Point> q = new ArrayDeque<>();
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[N][M];
for (int i = 0; i < N; i++) {
String s = br.readLine();
for (int j = 0; j < s.length(); j++) {
arr[i][j] = s.charAt(j) - '0';
}
}
br.close(); // 입력 끝
int[][] visited = new int[N][M];
result = bfs(0, 0, visited);
System.out.println(result);
}
static int bfs(int x, int y, int[][] visited) {
q.add(new Point(x, y, 1));
visited[x][y] = 1;
int result = Integer.MAX_VALUE;
while (!q.isEmpty()) {
Point p = q.poll();
int cnt = p.cnt;
// System.out.println(p.x + " " + p.y + " " + p.cnt);
if (p.x == N - 1 && p.y == M - 1) {
result = Math.min(result, p.cnt);
}
for (int i = 0; i < 4; i++) {
int nx = p.x + dx[i];
int ny = p.y + dy[i];
// 범위를 벗어나지 않는다면
if(0 <= nx && nx < N && 0 <= ny && ny < M) {
// 방문 전이고 갈 수 있는 길이면
if (visited[nx][ny] == 0 && arr[nx][ny] == 1) {
visited[nx][ny] = 1;
q.add(new Point(nx, ny, cnt + 1));
}
}
}
}
return result;
}
}
class Point {
int x, y;
int cnt;
Point(int x, int y, int cnt) {
this.x = x;
this.y = y;
this.cnt = cnt;
}
}