https://school.programmers.co.kr/learn/courses/30/lessons/1844
기본적인 BFS 문제
import java.util.LinkedList;
import java.util.Queue;
class point{
int x;
int y;
public point(int x, int y){
this.x = x;
this.y = y;
}
}
class Solution {
int[][] visited;
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0}; // 상하좌우
public int solution(int[][] maps) {
int answer = 0;
int n = maps.length;
int m = maps[0].length;
visited = new int[n][m];
// bfs
BFS(n, m, maps, visited, new point(0, 0));
answer = visited[n-1][m-1] > 0 ? visited[n-1][m-1] : -1;
return answer;
}
public void BFS(int n, int m, int[][] maps, int[][] visited, point start){
Queue<point> q = new LinkedList<>();
q.add(start);
visited[start.x][start.y] = 1;
while(!q.isEmpty()){
point now = q.poll();
for(int i=0; i<4; i++){
int nextX = now.x + dx[i];
int nextY = now.y + dy[i];
if(nextX >= 0 && nextY >= 0 && nextX < n && nextY < m && maps[nextX][nextY] == 1 && visited[nextX][nextY] == 0){
q.add(new point(nextX, nextY));
visited[nextX][nextY] = visited[now.x][now.y]+1;
}
}
}
}
}