BOJ - 2178번_미로 탐색 (C++)
BOJ - 2178번_미로 탐색
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램 작성하기
풀이
출발점부터 BFS를 시작해 값이 1인 곳만 방문하며 진행한다. dist배열을 이용해 출발점과의 거리를 담는다.
소스코드
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
vector<int> board[505];
int dist[505][505];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for(int i=0; i<n; i++) {
string s;
cin >> s;
for(auto c: s) {
board[i].push_back(c-'0');
}
fill(dist[i], dist[i]+m, -1);
}
queue<pair<int,int>> q;
q.push({0,0});
dist[0][0] = 0;
while(!q.empty()) {
pair<int,int> cur = q.front();
q.pop();
for(int k=0; k<4; k++) {
int nx = cur.X + dx[k];
int ny = cur.Y + dy[k];
if(nx<0 || nx>=n || ny<0 || ny>=m) continue;
if(dist[nx][ny]>0 || !board[nx][ny]) continue;
dist[nx][ny] = dist[cur.X][cur.Y]+1;
q.push({nx,ny});
}
}
cout << dist[n-1][m-1]+1;
}