난이도 : 실버 1
유형 : BFS
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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
BFS인지 DFS인지 고민하다 둘다 시간초과가 안날줄 알고 DFS로 구현했는데 시간초과가 나서 BFS로 바꿔줬다..
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* BOJ_2178_S1_미로탐색
* @author mingggkeee
* BFS,DFS,그래프
*/
public class BOJ_2178 {
static int R,C;
static int answer = Integer.MAX_VALUE;
static int[][] map;
static boolean[][] isVisited;
static int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
R = sc.nextInt();
C = sc.nextInt();
sc.nextLine();
map = new int[R][C];
isVisited = new boolean[R][C];
for(int r=0;r<R;r++) {
String str = sc.nextLine();
for(int c=0;c<C;c++) {
map[r][c] = str.charAt(c)-'0';
}
}
// dfs(0,0,1);
bfs();
// System.out.println(answer);
System.out.println(map[R-1][C-1]);
sc.close();
}
public static void bfs() {
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[] {0,0});
while(!queue.isEmpty()) {
int temp[] = queue.poll();
int r = temp[0];
int c = temp[1];
for(int i=0; i<4; i++) {
int nr = r + dir[i][0];
int nc = c + dir[i][1];
if(nr>=0 && nc>=0 && nr<R && nc<C && map[nr][nc] == 1 && !isVisited[nr][nc]) {
queue.offer(new int[] {nr,nc});
map[nr][nc] = map[r][c] + 1;
isVisited[nr][nc] = true;
}
}
}
}
public static void dfs(int r, int c, int count) {
if(count > answer) {
return;
}
if(r==R-1 && c==C-1) {
answer = Math.min(count, answer);
return;
}
isVisited[r][c] = true;
for(int i=0; i<4; i++) {
int nr = r+dir[i][0];
int nc = c+dir[i][1];
if(nr>=0 && nc>=0 && nr<R && nc<C && map[nr][nc] == 1 && !isVisited[nr][nc]) {
isVisited[nr][nc] = true;
dfs(nr,nc,count+1);
isVisited[nr][nc] = false;
}
}
}
}