[PS] 99ν΄λ½ μ½ν μ€ν°λ 33μΌμ°¨ TIL (리μ½μ³ λ‘λ΄)
νκ·Έ: 99ν΄λ½, BFS/DFS, PS, TIL, κ·Έλν, μ½λ©ν μ€νΈμ€λΉ, νν΄99
μΉ΄ν κ³ λ¦¬: PS
λ¬Έμ
μ€λͺ
μ κ·Έλ¦Όμ²λΌ βRβ μμ μΆλ°ν΄ μνμ’μ°λ‘ μμ§μΌ μ μλλ° μ΄μ κΉμ§ νμ΄λ΄€λ BFS/DFS λ¬Έμ μ λ€λ₯Έμ μ ν μΉΈμ© μμ§μ΄λ©΄μ μνμ’μ°λ₯Ό νμν΄κ°λ λ°©μμ΄ μλλΌ
- βDβ λ₯Ό λ§λ λ κΉμ§ μμ§μ΄κ±°λ
- 격μμ λ λΆλΆμ λ§λ λ κΉμ§ μμ§μΈλ€.
μμμ κ²½μ° λΉ¨κ° νμ΄ν λλ‘ μ΄ 7λ² μμ§μ΄λ©΄ βRβ μμ βGβ κΉμ§ κ° μ μλ μ΅λ¨ κ²½λ‘κ° λλ€.
νμ΄
μ΄μ κΉμ§μ λ¬Έμ λ μ£Όλ‘ DFS λ‘ νμλλ° μ΄λ² λ¬Έμ λ BFS λ‘ νΈλ κ²μ΄ λ μ μ νλ€. DFS λ‘ νΈλ κ²½μ° μ΅λ¨ κ²½λ‘μΈμ§ νμΈνλ λ‘μ§μ΄ μΆκ°λ‘ νμνλ€.
νμμ μμν βRβ μ μμΉλ₯Ό μ°Ύμ ν BFS λ₯Ό μμνλ€. bfs
ν¨μμμλ βRβ μμ μΆλ°ν΄ βGβ μ λλ¬ν λ κΉμ§μ μ μ κ°μ 거리λ₯Ό ꡬν΄μ£Όλ©΄ λλ€.
μ μ κ°μ 거리λ₯Ό ꡬν λ dist λ³μλ₯Ό dfs ν¨μμ μΈμλ‘ μ λ¬νκ±°λ bfs μ κ²½μ° queue μ λ£μ΄μ£Όλ μμΌλ‘ ꡬνλ©΄ λλ€.
μ₯μ λ¬Όμ λ§λκ±°λ λ²½μ λλ¬ν λ κΉμ§ μ μ΄λν ν, κ·Έ λ
Έλκ° μμ§ λ°©λ¬Έ μ μ΄λΌλ©΄ λ°©λ¬Έμ²λ¦¬λ₯Ό ν΄μ£Όκ³ λ€μ νμμ μν΄ queue μ μ’νλ₯Ό λ£μ΄μ€λ€. μ΄λ, dist + 1
μ λ겨μ€μ λ
Έλ κ° μ΄λ 거리λ₯Ό κ³μ°ν΄ μ€λ€.
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
class Solution {
static String[][] graph;
static boolean[][] visited;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static int n;
public int solution(String[] board) {
n = board.length;
graph = new String[n][];
visited = new boolean[n][];
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
graph[i] = new String[board[i].length()];
visited[i] = new boolean[board[i].length()];
char[] charArray = board[i].toCharArray();
for (int j = 0; j < charArray.length; j++) {
String s = String.valueOf(charArray[j]);
graph[i][j] = s;
if (s.equals("R")) {
x = i;
y = j;
}
}
}
return bfs(x, y);
}
private int bfs(int x, int y) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] {x, y, 0});
visited[x][y] = true;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int cx = current[0];
int cy = current[1];
int dist = current[2];
if (graph[cx][cy].equals("G")) {
return dist;
}
for (int i = 0; i < 4; i++) {
int nx = cx;
int ny = cy;
while (isInRange(nx + dx[i], ny + dy[i]) && !graph[nx + dx[i]][ny + dy[i]].equals("D")) {
nx += dx[i];
ny += dy[i];
}
if (!visited[nx][ny]) {
visited[nx][ny] = true;
queue.add(new int[] {nx, ny, dist + 1});
}
}
}
return -1;
}
private boolean isInRange(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < graph[x].length;
}
}
λκΈλ¨κΈ°κΈ°