https://school.programmers.co.kr/learn/courses/30/lessons/1844
import java.util.*;
class Point {
public int x, y;
Point (int x, int y) {
this.x = x;
this.y = y;
}
}
class Solution {
int[] dx = {-1 , 0, 1, 0};
int[] dy = {0, 1, 0, -1};
int n, m;
int[][] route, dis;
public void BFS(int x, int y) {
Queue<Point> q = new LinkedList<>();
q.offer(new Point(x,y));
route[x][y] = 0;
dis[x][y] = 1;
while(!q.isEmpty()) {
Point tmp = q.poll();
for (int i=0; i<4; i++) {
int nx = tmp.x + dx[i];
int ny = tmp.y + dy[i];
if (nx >=0 && nx <= n && ny >=0 && ny <=m && route[nx][ny] == 1) {
route[nx][ny] = 0;
q.offer(new Point(nx,ny));
dis[nx][ny] = dis[tmp.x][tmp.y] + 1;
}
}
}
}
public int solution(int[][] maps) {
n = maps.length - 1;
m = maps[0].length - 1;
route = maps;
dis = new int[n+1][m+1];
BFS(0,0);
if (dis[n][m] == 0) return -1;
else return dis[n][m];
}
}