링크텍스트

import java.util.*;
import java.io.*;
class Main {
static int n,m;
static char[][]arr;
static boolean[][] check;
static int [] dx = {0,0,1,-1};
static int [] dy = {1,-1,0,0};
static int total = 0;
static Queue<int []> q = new LinkedList<>();
static StringBuilder sb = new StringBuilder();
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 char[n][m];
check = new boolean[n][m];
for(int i=0;i<n;i++){
String s = br.readLine();
for(int j=0;j<m;j++){
arr[i][j] = s.charAt(j);
}
}
bfs(0,0);
System.out.println(total);
}
public static void bfs(int x,int y){
q.add(new int[]{x,y});
check[x][y] = true;
while(!q.isEmpty()){
int size = q.size();
total++;
for(int i=0;i<size;i++){
int [] point = q.poll();
int cx = point[0];
int cy = point[1];
if(cx==n-1&&cy==m-1){
return;
}
for(int j=0;j<4;j++){
int xx = cx+dx[j];
int yy = cy+dy[j];
if(xx>=0 && xx<n && yy>=0 && yy<m && arr[xx][yy]=='1'&&!check[xx][yy]){
q.add(new int[] {xx,yy});
check[xx][yy]=true;
}
}
}
}
}
}
