문제풀이(JAVA)
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] maze = new int[n][m];
for(int i = 0; i<n; i++) {
maze[i] = Arrays.stream(br.readLine().split("")).mapToInt(Integer::parseInt).toArray();
}
escapeMaze(maze);
}
public static void escapeMaze(int[][] maze) {
boolean[][] visited = new boolean[maze.length][maze[0].length];
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
Queue<Position> queue = new LinkedList<>();
queue.offer(new Position(0,0));
visited[0][0] = true;
while(!queue.isEmpty()) {
Position p = queue.poll();
for(int i=0; i<4; i++) {
int x = p.getX()+dx[i];
int y = p.getY()+dy[i];
if(x < 0 || x >= maze.length || y < 0 || y >= maze[0].length) {
continue;
}
if(maze[x][y] != 0 && visited[x][y] == false) {
queue.offer(new Position(x, y));
visited[x][y] = true;
if(maze[x][y] == 1 || maze[x][y] > maze[p.getX()][p.getY()] + 1) {
maze[x][y] = maze[p.getX()][p.getY()] + 1;
}
}
}
}
System.out.print(maze[maze.length-1][maze[0].length-1]);
}
public static class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
}