Algorithm/백준
[백준] 2178번 미로 탐색
sirius
2021. 3. 11. 10:10
https://www.acmicpc.net/problem/2178
2178번: 미로 탐색
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
www.acmicpc.net
import java.util.*;
import java.io.*;
class Node {
int y;
int x;
Node(int y, int x) {
this.y = y;
this.x = x;
}
}
public class Main {
static int N;
static int M;
static int[][] map;
static boolean[][] visit;
static int[] dy = { 0, 1, 0, -1 };
static int[] dx = { 1, 0, -1, 0 };
public static void main(String[] args) throws Exception {
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];
visit = new boolean[N][M];
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < M; j++) {
map[i][j] = input.charAt(j) - '0';
}
}
bfs(0, 0);
System.out.println(map[N-1][M-1]);
}
public static void bfs(int y, int x) {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(0, 0));
visit[0][0] = true;
while (!q.isEmpty()) {
Node node = q.poll();
int ny = node.y;
int nx = node.x;
for (int i = 0; i < 4; i++) {
int nextY = ny + dy[i];
int nextX = nx + dx[i];
// 벽의 범위 벗어남
if (nextY < 0 || nextY >= N || nextX < 0 || nextX >= M) {
continue;
}
// 맵이 0이거나, 이미 방문했을 대 통과
if (map[nextY][nextX] == 0 || visit[nextY][nextX]) {
continue;
}
// 큐에 추가
q.offer(new Node(nextY, nextX));
// 방문처리
visit[nextY][nextX] = true;
// 거리 누적
map[nextY][nextX] = map[ny][nx] + 1;
}
}
}
}