백준 2178 미로 탐색

aiden·2025년 12월 13일

백준 문제풀이

목록 보기
11/11

문제 링크 : https://www.acmicpc.net/problem/2178

의사 코드 :

붙여서 입력받으므로 입력을 string으로 일단 받는다
for 0~n까지
cin >> 입력

for 0~n까지
fill로 전체 거리 저장배열 -1로 초기화 // 이렇게 하면 hasVisited없이도 방문 여부 확인할 수 있음!


bfs는 항상 최단경로를 보장하므로 이 이후는 그냥 일반 BFS 구현하듯 한다.

코드 :

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

/*
N×M크기의 배열로 표현되는 미로가 있다.

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다.
이러한 미로가 주어졌을 때,
(1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오.
한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.


*/

string arr[102]; // 붙어서 입력이 된다
int dist[102][102];
bool hasVisited[501][501];

int n, m;

int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> n >> m;

	for (int i = 0; i < n; i++) {
		cin >> arr[i];
	}

	for (int i = 0; i < n; i++) {
		fill(dist[i], dist[i] + m, -1);
	}
	queue<pair<int, int>> q;

	q.push({ 0, 0 });
	dist[0][0] = 0;
	while (q.empty() == false) {
		pair<int, int> cur = q.front();
		q.pop();

		for (int dir = 0; dir < 4; dir++) {
			int nx = cur.first + dx[dir];
			int ny = cur.second + dy[dir];


			if (nx < 0 || nx >= n || ny < 0 || ny >= m)
				continue;
			if (dist[nx][ny] >= 0 || arr[nx][ny] != '1') {
				continue;
			}

			dist[nx][ny] = dist[cur.first][cur.second] + 1;

			q.push({ nx, ny });
		}
	}

	cout << dist[n - 1][m - 1] + 1;
}

일반적인 BFS와 비슷하게 구현하되 시작점과의 거리를 전부 계산한다.

profile
All's well that ends well

0개의 댓글