https://www.acmicpc.net/problem/2178
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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
처음에 정신줄 놓고 DFS로 풀어서 최단경로를 못찾았다.
BFS를 이용하면 간단하게 풀 수 있다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class maze_2178 {
static int[] dx = {1,-1,0,0};
static int[] dy = {0,0,1,-1};
static int count = 0;
static int n,m;
//static boolean[][] check;
static int[][] visit;
static int[][] arr;
public static void solution() throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new int[n][m];
//check = new boolean[n][m];
visit = new int[n][m];
for(int i=0;i<n;i++){
String tmp = bf.readLine();
for(int j=0;j<m;j++){
if(tmp.charAt(j)=='1'){
arr[i][j]= 1;
}
}
Arrays.fill(visit[i],-1);
}
BFS(0,0);
System.out.println(visit[n-1][m-1]+1);
}
public static void BFS(int x, int y){
Queue<int[]> queue = new LinkedList<>();
//check[x][y] = true;
visit[x][y] = 0;
queue.add(new int[]{x,y});
while(!queue.isEmpty()){
int[] tmp = queue.poll();
for(int i=0;i<4;i++){
int nx = tmp[0]+dx[i];
int ny = tmp[1]+dy[i];
if(nx>=0 && ny>=0 && nx<n && ny<m){
if(visit[nx][ny]==-1 && arr[nx][ny]==1){
//System.out.println(nx+" "+ny+" ");
visit[nx][ny] = visit[tmp[0]][tmp[1]]+1;
queue.add(new int[]{nx,ny});
//check[nx][ny] = true;
}
}
}
}
}
}