-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ2178.java
More file actions
87 lines (69 loc) · 2.41 KB
/
BOJ2178.java
File metadata and controls
87 lines (69 loc) · 2.41 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
79
80
81
82
83
84
85
86
87
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class BOJ2178 {
static int n, m;
static int[][] arrayMap;
static int[][] direction = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
static int[][] distance;
static boolean[][] visited;
private static void input() 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());
arrayMap = new int[n][m];
distance = new int[n][m];
visited = new boolean[n][m];
String tmpStr;
for (int i = 0; i < n; i++) {
tmpStr = br.readLine();
for (int j = 0; j < m; j++) {
arrayMap[i][j] = tmpStr.charAt(j) - '0';
}
}
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process() {
// bfs
bfs(0, 0);
// answer print
System.out.println(distance[n - 1][m - 1]);
}
private static void bfs(int y, int x) {
Queue<Integer> queue = new LinkedList<>();
queue.add(y);
queue.add(x);
visited[y][x] = true;
// 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
distance[y][x] = 1;
while (!queue.isEmpty()) {
int thisY = queue.poll();
int thisX = queue.poll();
for (int i = 0; i < 4; i++) {
int nextY = thisY + direction[i][0];
int nextX = thisX + direction[i][1];
if (nextY < 0 || nextX < 0 || nextY >= n || nextX >= m) continue;
if (visited[nextY][nextX]) continue;
if (arrayMap[nextY][nextX] != 1) continue;
queue.add(nextY);
queue.add(nextX);
visited[nextY][nextX] = true;
distance[nextY][nextX] = distance[thisY][thisX] + 1;
}
}
}
private static void printArray(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < arrayMap[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}