https://school.programmers.co.kr/learn/courses/30/lessons/1844?language=java
문제 풀이
import java.util.*;
class Solution {
static int visited[][];
static Queue<Node> queue;
static int dx[] = {0, 1, 0, -1};
static int dy[] = {1, 0, -1, 0};
public int solution(int[][] maps) {
int answer = 0;
int n = maps.length;
int m = maps[0].length;
visited = new int[n][m];
queue = new LinkedList<>();
bfs(maps, n, m);
answer = visited[n - 1][m - 1];
if (answer == 0) answer = -1;
return answer;
}
public static void bfs(int[][] maps, int n, int m) {
visited[0][0] = 1;
queue.add(new Node(0, 0));
while (!queue.isEmpty()) {
Node node = queue.poll();
for (int k = 0; k < 4; k++) {
int nx = node.x + dx[k];
int ny = node.y + dy[k];
if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
if (visited[nx][ny] == 0 && maps[nx][ny] == 1) {
visited[nx][ny] = visited[node.x][node.y] + 1;
queue.add(new Node(nx, ny));
}
}
}
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
'알고리즘 > 탐색' 카테고리의 다른 글
[백준] 4673 셀프 넘버 (완전탐색) - Java (1) | 2023.05.10 |
---|---|
[백준] 1759 암호 만들기 (완전탐색) - Java (1) | 2023.05.10 |
[백준] 2110 공유기 설치 (이분탐색) - Java (0) | 2023.05.03 |
[백준] 1926 그림 (BFS) - Java (0) | 2023.04.19 |
[백준] 5014 스타트링크 (BFS) - Java (0) | 2023.04.19 |