문제
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));
}
}
}
}
'Algorithm' 카테고리의 다른 글
[백준/DFS] 11725 - 트리의 부모 찾기 (0) | 2019.09.15 |
---|---|
[백준/DFS] 2667 - 단지번호붙이기 (0) | 2019.09.08 |
[백준/DP] 1149 - RGB거리 (0) | 2019.09.01 |
[백준/DP] 1932 - 정수 삼각형 (0) | 2019.09.01 |
[백준/DP] 1003 - 피보나치 함수 (0) | 2019.09.01 |