import java.util.*;
class Solution {
static int[] dx = {-1, 1, 0 , 0};
static int[] dy = {0, 0, -1, 1};
public int solution(int[][] maps) {
int answer = 0;
int[][] ch = new int[maps.length][maps[0].length];
bfs(maps, ch);
answer = ch[maps.length-1][maps[0].length-1];
if(answer == 0){
answer = -1;
}else{
return answer;
}
return answer;
}
public static void bfs(int[][] maps, int[][] ch){
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
ch[0][0] =1;
while(!queue.isEmpty()){
int[] now= queue.poll();
int x = now[0];
int y = now[1];
for(int i=0; i<4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0 && nx<maps.length
&& ny>=0 && ny<maps[0].length
&& ch[nx][ny] == 0 && maps[nx][ny] == 1){
ch[nx][ny] = ch[x][y]+1;
queue.offer(new int[]{nx, ny});
}
}
}
}
}