forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path11.java
79 lines (65 loc) ยท 2.22 KB
/
11.java
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
import java.util.*;
class Node {
private int x;
private int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Main {
public static int n, m;
public static int[][] graph = new int[201][201];
// ์ด๋ํ ๋ค ๊ฐ์ง ๋ฐฉํฅ ์ ์ (์, ํ, ์ข, ์ฐ)
public static int dx[] = {-1, 1, 0, 0};
public static int dy[] = {0, 0, -1, 1};
public static int bfs(int x, int y) {
// ํ(Queue) ๊ตฌํ์ ์ํด queue ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
Queue<Node> q = new LinkedList<>();
q.offer(new Node(x, y));
// ํ๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณตํ๊ธฐ
while(!q.isEmpty()) {
Node node = q.poll();
x = node.getX();
y = node.getY();
// ํ์ฌ ์์น์์ 4๊ฐ์ง ๋ฐฉํฅ์ผ๋ก์ ์์น ํ์ธ
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// ๋ฏธ๋ก ์ฐพ๊ธฐ ๊ณต๊ฐ์ ๋ฒ์ด๋ ๊ฒฝ์ฐ ๋ฌด์
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
// ๋ฒฝ์ธ ๊ฒฝ์ฐ ๋ฌด์
if (graph[nx][ny] == 0) continue;
// ํด๋น ๋
ธ๋๋ฅผ ์ฒ์ ๋ฐฉ๋ฌธํ๋ ๊ฒฝ์ฐ์๋ง ์ต๋จ ๊ฑฐ๋ฆฌ ๊ธฐ๋ก
if (graph[nx][ny] == 1) {
graph[nx][ny] = graph[x][y] + 1;
q.offer(new Node(nx, ny));
}
}
}
// ๊ฐ์ฅ ์ค๋ฅธ์ชฝ ์๋๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ ๋ฐํ
return graph[n - 1][m - 1];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// N, M์ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์ฌ ์
๋ ฅ ๋ฐ๊ธฐ
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine(); // ๋ฒํผ ์ง์ฐ๊ธฐ
// 2์ฐจ์ ๋ฆฌ์คํธ์ ๋งต ์ ๋ณด ์
๋ ฅ ๋ฐ๊ธฐ
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
for (int j = 0; j < m; j++) {
graph[i][j] = str.charAt(j) - '0';
}
}
// BFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ ์ถ๋ ฅ
System.out.println(bfs(0, 0));
}
}