문제
N×M크기의 배열로 표현되는 미로가 있다.
1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.
위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
입력
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
출력
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
예제 입력 1
4 6
101111
101010
101011
111011
예제 출력 1
15
예제 입력 2
4 6
110110
110110
111111
111101
예제 출력 2
9
예제 입력 3
2 25
1011101110111011101110111
1110111011101110111011101
예제 출력 3
38
예제 입력 4
7 7
1011111
1110001
1000001
1000001
1000001
1000001
1111111
예제 출력 4
13
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* Created by mkhwang on 2021/04/02
* Email : orange2652@gmail.com
* Github : http://github.com/myeongkwonhwang
*/
public class Boj2178 {
static int X;
static int Y;
static int maze[][];
static int dist[][];
static int [] dx = {1, 0, -1, 0}; //아래부터 반시계방향
static int [] dy = {0, 1, 0, -1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
X = Integer.parseInt(st.nextToken());
Y = Integer.parseInt(st.nextToken());
maze = new int[X][Y];
dist = new int[X][Y];
for (int i = 0; i < X; i++) {
st = new StringTokenizer(br.readLine());
String line = st.nextToken();
for (int j = 0; j < Y; j++) {
maze[i][j] = line.charAt(j) - '0';
dist[i][j] = -1;
}
}
dist[0][0] = 0;
bfs(0,0);
System.out.println(dist[X-1][Y-1]+1);
}
private static void bfs(int x, int y) {
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(x, y));
while (!queue.isEmpty()){
Node curr = queue.poll();
for (int dir = 0; dir < 4; dir++) {
int nx = curr.getX() + dx[dir];
int ny = curr.getY() + dy[dir];
if(nx < 0 || nx >= X || ny < 0 || ny >= Y) continue;
if(dist[nx][ny] >= 0 || maze[nx][ny] == 0) continue;
dist[nx][ny] = dist[curr.x][curr.y]+1;
queue.add(new Node(nx, ny));
}
}
}
public static class Node {
private int x;
private int y;
public Node(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
}