📍 문제 설명
💡 접근
전형적인 BFS 문제
👩💻 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int n, m, v, e, k, answer, cnt;
static int[][] board;
static int[] arr;
static long[] dp;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static ArrayList<Integer> list = new ArrayList<>();
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
Main T = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = kb.nextInt();
m = kb.nextInt();
kb.nextLine();
board = new int[n+1][m+1];
visited = new boolean[n+1][m+1];
for(int i = 1; i <= n; i++) {
String[] s = kb.nextLine().split("");
for(int j = 0; j < m; j++) {
board[i][j+1] = Integer.parseInt(s[j]);
}
}
T.solution();
System.out.println(board[n][m]);
}
private void solution() {
Queue<Point> q = new LinkedList<>();
q.offer(new Point(1, 1));
visited[1][1] = true;
while(!q.isEmpty()) {
Point cp = q.poll();
for(int i = 0; i < 4; i++) {
int nx = cp.x + dx[i];
int ny = cp.y + dy[i];
if(nx<=0 || ny<=0 || nx>n || ny>m) continue;
if(board[nx][ny] == 1 && !visited[nx][ny]) {
visited[nx][ny] = true;
board[nx][ny] = board[cp.x][cp.y] + 1;
q.offer(new Point(nx, ny));
}
}
}
}
private class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}