코딩테스트
[백준] 2178 미로탐색 자바
엥이게되네
2023. 8. 3. 23:52
728x90
https://www.acmicpc.net/problem/2178
2178번: 미로 탐색
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
www.acmicpc.net
문제
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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
출력
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
import java.io.*;
import java.util.*;
// 미로 탐색
public class BOJ_2178 {
static int n;
static int m;
static int[][] map;
static boolean[][] visited;
static int[] dy = { -1, 0, +1, 0 };
static int[] dx = { 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());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
map = new int[n][m];
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (int j = 0; j < m; j++) {
map[i][j] = str.charAt(j) - '0';
}
}
visited = new boolean[n][m];
visited[0][0] = true;
bfs(0, 0);
System.out.println(map[n-1][m-1]);
}
public static void bfs(int y, int x) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[] {y, x});
while (!q.isEmpty()) {
int cur[] = q.poll();
int cy = cur[0];
int cx = cur[1];
for (int dir = 0; dir < 4; dir++) {
int ny = cy + dy[dir];
int nx = cx + dx[dir];
if (ny < 0 || nx < 0 || ny >= n || nx >= m)
continue;
if (visited[ny][nx] || map[ny][nx] == 0)
continue;
q.add(new int[] {ny, nx});
map[ny][nx] = map[cy][cx] + 1;
visited[ny][nx] = true;
}
}
}
}
728x90