https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

	static int N, M;
	static int[][] map;
	static int[] dr = { -1, 1, 0, 0 };
	static int[] dc = { 0, 0, -1, 1 };

	static class Pos {
		int r, c;

		public Pos(int r, int c) {
			this.r = r;
			this.c = c;
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		N = sc.nextInt();
		M = sc.nextInt();
		map = new int[N][M];
		sc.nextLine();

		for (int i = 0; i < N; i++) {
			String str = sc.nextLine();
			for (int j = 0; j < M; j++) {
				map[i][j] = str.charAt(j) - '0';
			}
		}

		bfs();
		System.out.println(map[N - 1][M - 1]);
	}

	private static void bfs() {
		Queue<Pos> q = new LinkedList<>();

		q.offer(new Pos(0, 0));

		while (!q.isEmpty()) {
			Pos curr = q.poll();

			// 현재 위치에서 사방탐색
			for (int dir = 0; dir < 4; dir++) {
				int nr = curr.r + dr[dir];
				int nc = curr.c + dc[dir];

				// 범위 벗어나거나 벽인 경우
				if (!isRange(nr, nc) || map[nr][nc] != 1) {
					continue;
				}

				// 처음 방문하는 경우에만 최단 거리 기록
				if (map[nr][nc] == 1) {
					// 이전 위치 + 1
					map[nr][nc] = map[curr.r][curr.c] + 1;
					q.offer(new Pos(nr, nc));
				}
			}
		}
	}

	private static boolean isRange(int r, int c) {
		// 범위 체크
		return ((r >= 0) && (r < N) && (c >= 0) && (c < M));
	}
}

+ Recent posts