문제
입력 및 출력
풀이
import java.io.*;
import java.util.*;
class Main {
public static int N;
public static int M;
public static int[][] map;
public static int count = 0;
public static boolean[][] visited;
public static int[] px = {0, 1, 0, -1};
public static int[] py = {-1, 0, 1, 0};
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
N = Integer.parseInt(input[0]);
M = Integer.parseInt(input[1]);
map = new int[N][M];
visited = new boolean[N][M];
for(int i = 0; i < N; i++) {
String[] temp = br.readLine().split("");
for(int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(temp[j]);
}
}
BFS();
}
public static void BFS() {
Queue<Node> queue = new LinkedList<>();
Node node = new Node(0, 0, 1);
queue.offer(node);
visited[0][0] = true;
while(!queue.isEmpty()) {
Node temp = queue.poll();
if(temp.x == N-1 && temp.y == M-1) {
System.out.println(temp.count);
break;
}
for(int i = 0; i < 4; i++) {
int nx = temp.x + px[i];
int ny = temp.y + py[i];
if(nx >= 0 && ny >= 0 && nx < N && ny < M) {
if(!visited[nx][ny] && map[nx][ny] == 1) {
queue.offer(new Node(nx, ny, temp.count + 1));
visited[nx][ny] = true;
}
}
}
}
}
}
class Node {
int x;
int y;
int count;
public Node(int x, int y, int count) {
this.x = x;
this.y = y;
this.count = count;
}
}
결과 및 해결방법
[결과]