1. ๋ฌธ์ :https://school.programmers.co.kr/learn/courses/30/lessons/1844
2. ํ์ด
์ต๋จ๊ฑฐ๋ฆฌ์ ๊ฒฝ์ฐ bfs๋ก!
3. ์ฝ๋
import java.util.*;
class Solution {
// ์ํ์ข์ฐ ์ด๋ํ ์ ์๋ ์ขํ
int[] dx = {0, 1, -1, 0};
int[] dy = {1, 0, 0, -1};
public int solution(int[][] maps) {
int answer = 0;
int[][] visited = new int[maps.length][maps[0].length];
bfs(maps, visited);
answer = visited[maps.length - 1][maps[0].length - 1]; // ์๋ ํ ์ง์ ์ขํ
if (answer == 0) { // ์๋ ํ ์ง์์ ๋๋ฌํ์ง ๋ชปํ ๊ฒฝ์ฐ
answer = -1;
}
return answer;
}
public void bfs(int[][] maps, int[][] visited) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{0, 0}); // Queue์ ์์ ์ ์ ์ถ๊ฐ
visited[0][0] = 1;
while (!q.isEmpty()) { // ๋ ๋์๊ฐ ์ ์ ์ด ์์ ๋๊น์ง ๋ฐ๋ณต
int[] current = q.poll(); // ์ ์ ํ๋ ๊บผ๋ด๊ธฐ
int X = current[0];
int Y = current[1];
for (int i = 0; i < 4; i++) {
int nX = X + dx[i];
int nY = Y + dy[i];
// ์ขํ๊ฐ maps์์ ๋ฒ์ด๋ ๊ฒฝ์ฐ ๋ค์ ๋ฐ๋ณต์ผ๋ก ๋์ด๊ฐ๋ค
if (nX < 0 || nX > maps.length - 1 || nY < 0 || nY > maps[0].length - 1) {
continue;
}
// ์์ง ๋ฐฉ๋ฌธํ์ง ์์๊ณ , ๋ฒฝ์ด ์๋ ๊ฒฝ์ฐ
if (visited[nX][nY] == 0 && maps[nX][nY] == 1) {
visited[nX][nY] = visited[X][Y] + 1;
q.add(new int[]{nX, nY});
}
}
}
}
}
'๐ป Coding Problems Solving > DFS | BFS | Backtracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ 2178] ๋ฏธ๋ก ํ์ (java) (0) | 2023.04.11 |
---|---|
[BOJ 1062] ๊ฐ๋ฅด์นจ (java) (0) | 2023.04.04 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ํ๋ ์ฆ4๋ธ๋ก (0) | 2023.03.13 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ํผ๋ก๋ (์๋ฐ java) (0) | 2023.03.01 |
[BOJ 1303] ์ ์-์ ํฌ (0) | 2022.07.04 |
์ต๊ทผ๋๊ธ