본문 바로가기

알고리즘/백준 문제풀이

[백준 2178번] 미로 탐색 / C++

문제

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

출력

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

풀이

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

int x_idx[4] = { -1, 0, 0, 1 };
int y_idx[4] = { 0, -1, 1, 0 };

void bfs(queue<pair<int, int>> need_visit, int visited[][100], int N, int M, int arr[][100]) {

	while (!need_visit.empty()) {
		int cur_x = need_visit.front().first;
		int cur_y = need_visit.front().second;
		need_visit.pop();

		for (int i = 0; i < 4; i++) {
			int next_x = cur_x + x_idx[i];
			int next_y = cur_y + y_idx[i];
			if (next_x < 0 || next_x >= N || next_y < 0 || next_y >= M)
				continue;
			if (arr[next_x][next_y] == 1 && visited[next_x][next_y] == 0) {
				visited[next_x][next_y] = visited[cur_x][cur_y] + 1;
				need_visit.push(make_pair(next_x, next_y));
			}
		}
	}

}

int main() {
	int N, M, answer;
	int visited[100][100] = { 1, };
	int arr[100][100];
	queue<pair<int, int>> need_visit;

	cin >> N >> M;

	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++) {
			scanf("%1d", &arr[i][j]);
		}
	}

	need_visit.push(make_pair(0, 0));
	
	bfs(need_visit, visited, N, M, arr);

	answer = visited[N - 1][M - 1];

	cout << answer;

}