-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
56 lines (44 loc) · 1.33 KB
/
Solution.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
//
// BFS(게임 맵 최단거리)
// https://programmers.co.kr/learn/courses/30/lessons/1844
// Created by hyungwook on 2022/02/03.
//
import java.util.LinkedList;
public class Solution {
public int solution(int[][] maps) {
int r = maps.length;
int c = maps[0].length;
LinkedList<Point> queue = new LinkedList<>();
queue.add(new Point(0, 0));
maps[0][0] = 0;
int l = 1;
int[][] dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Point poll = queue.poll();
for (int j = 0; j < 4; j++) {
int rx = poll.r + dir[j][0];
int cx = poll.c + dir[j][1];
if (rx == r - 1 && cx == c - 1) {
return l + 1;
}
if (rx >= 0 && rx < r && cx >= 0 && cx < c && maps[rx][cx] == 1) {
maps[rx][cx] = 0;
queue.add(new Point(rx, cx));
}
}
}
l++;
}
return -1;
}
static class Point {
int r;
int c;
public Point(int r, int c) {
this.r = r;
this.c = c;
}
}
}