Algorithm
[백준/BFS] 2178 - 미로 탐색
strawberry_toast
2019. 9. 8. 23:02
문제
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
4 6
101111
101010
101011
111011
예제 출력 1
15
내 소스
#include <iostream>
#include <queue>
using namespace std;
void BFS(int,int);
int** arr;
int n, m;
int main(int argc, const char * argv[]) {
int n, m;
string s;
cin >> n;
cin >> m;
arr = new int*[n];
for(int i=0; i<n; i++){
arr[i] = new int[m];
cin >> s;
for(int j=0; j<m; j++){
arr[i][j] = (int) s[j]-'0';
}
}
BFS(n,m);
for(int i=0; i<n; i++){
delete[] arr[i];
}
delete [] arr;
return 0;
}
void BFS(int n, int m){
int count = 0;
int breath_index, x, y;
queue< pair<pair<int, int>, int> > q;
bool** visited = new bool*[n];
for(int i=0; i<n; i++){
visited[i] = new bool[m];
}
q.push(make_pair(make_pair(0,0), 0));
while(!q.empty()){
count++;
pair<pair<int,int>, int> c = q.front();
q.pop();
breath_index = c.second;
x = c.first.first;
y = c.first.second;
if(!visited[x][y]){
visited[x][y] = true;
if(x == n-1 && y == m-1){
cout << breath_index+1;
}
if(x+1 < n && !visited[x+1][y] && arr[x+1][y] == 1){
q.push(make_pair(make_pair(x+1, y), breath_index+1));
}
if(y+1 < m && !visited[x][y+1] && arr[x][y+1] == 1){
q.push(make_pair(make_pair(x, y+1), breath_index+1));
}
if(y-1 >=0 && !visited[x][y-1] && arr[x][y-1] == 1){
q.push(make_pair(make_pair(x, y-1), breath_index+1));
}
if(x-1 >= 0 && !visited[x-1][y] && arr[x-1][y] == 1){
q.push(make_pair(make_pair(x-1, y), breath_index+1));
}
}
}
}