import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[] dx = {0, 1, 0, -1};
static int[] dy = {1, 0, -1, 0};
static boolean[][] visited;
static int[][] arr;
static int N, M;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new int[N][M];
visited = new boolean[N][M];
for (int i = 0; i < N; i++) {
String nums = br.readLine();
for (int j = 0; j < M; j++) {
arr[i][j] = Integer.parseInt(nums.substring(j, j + 1));
}
}
bfs(0, 0);
System.out.println(arr[N - 1][M - 1]);
}
private static void bfs(int i, int j) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i, j});
visited[i][j] = true;
while (!queue.isEmpty()) {
int[] now = queue.poll();
for (int k = 0; k < 4; k++) {
int x = now[0] + dx[k];
int y = now[1] + dy[k];
if (x >= 0 && y >= 0 && x < N && y < M) {
if (arr[x][y] != 0 && !visited[x][y]) {
visited[x][y] = true;
arr[x][y] = arr[now[0]][now[1]] + 1;
queue.add(new int[] {x, y});
}
}
}
}
}
}
'Coding Test > 백준' 카테고리의 다른 글
[백준/자바] 10814 - 나이순 정렬 (0) | 2023.08.07 |
---|---|
[백준/자바] 1167 - 트리의 지름 (0) | 2023.08.07 |
[백준/자바] 1260 - DFS와 BFS (0) | 2023.08.06 |
[백준/자바] 13023 - ABCDE (0) | 2023.08.04 |
[백준/자바] 2023 - 신기한 소수 (0) | 2023.08.04 |