본문 바로가기
코딩테스트 준비/JAVA 코테

백준2178. 미로탐색 (BFS)

by 김긍수 2021. 3. 26.

www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

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

www.acmicpc.net

문제제목 : 미로탐색

문제난이도 : 실버1

문제유형 : BFS

문제

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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

출력

첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.

 

아이디어

1. 최종위치까지의 최단거리를 구해야하므로 BFS를 이용한다. (BFS는 각 정점을 최단경로로 방문함)

2. 현재 지점(x, y)에서 지날 수 있는 길의 경우는 (x-1,y) (x+1,y), (x,y-1), (x,y+1) 위치가 1인경우이다.

3. 거리를 구하기 위해 다음 정점으로 갈때 현재 정점으로 오는 최단경로 + 1을 해준다.

 

package week4;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class BOJ2178 {
	private static int[][] map;
	private static boolean[][] visited;
	private static int[][] data;
	private static int N, M;
	private static int[] dx = {-1, 1, 0, 0};
	private static int[] dy = {0, 0, -1, 1};
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
        // N, M 입력
		String[] loc = br.readLine().split(" ");
		N = Integer.parseInt(loc[0]);
		M = Integer.parseInt(loc[1]);
		
        // 초기화
		map = new int[N][M];
		visited = new boolean[N][M];
		data = new int[N][M];
		
        // 미로 입력
		for (int i = 0; i < N; i++) {
			String[] input = br.readLine().split("");
			for (int j = 0; j < M; j++) {
				map[i][j] = Integer.parseInt(input[j]);
			}
		}
        
		// 너비우선탐색
		BFS(0,0);
		
        // 도착지 최단거리 출력
		System.out.println(data[N-1][M-1]);
	}
	
	public static void BFS(int x, int y) {
		Queue<loc> q = new LinkedList<>();
		q.add(new loc(x, y));
		visited[x][y] = true;
		data[x][y]++;
		
		while (!q.isEmpty()) {
			loc now = q.poll();
			
			if (now.x == N - 1 && now.y == M - 1) {
				// N,M에 도착했으면 종료
				return;
			}
			
			for (int i = 0; i < 4; i++) {
				int next_x = now.x + dx[i];
				int next_y = now.y + dy[i];
				
				if (next_x < 0 || next_y < 0 || next_x >= N || next_y >= M) {
					continue;
				}
				
				if (map[next_x][next_y] == 1 && !visited[next_x][next_y]) {
					data[next_x][next_y] = data[now.x][now.y] + 1;
					q.add(new loc(next_x, next_y));
					visited[next_x][next_y] = true;
				}
			}
		}
	}
}

class loc {
	int x;
	int y;
	
	public loc(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

 

댓글