bfs = 너비 우선 탐색
: 루트 노드에서 시작해서 인접한 노드를 먼저 탐색하는 방법.
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
int solution(vector<vector<int> > maps)
{
int answer = 0;
int n = maps.size();
int m = maps[0].size();
int go[3] = {-1, 0, 1};
int **visited = new int*[n];
queue<pair<int, int>> q;
for (int i = 0; i < n; i++)
visited[i] = new int[m]();
if ((maps[n - 1][m - 2] == 0) && (maps[n - 2][m - 1] == 0)) // 출구 없는 경우
return -1;
q.push(make_pair(0,0));
visited[0][0] = 1;
pair<int, int> tmp;
while (q.size())
{
tmp = q.front();
q.pop();
if ((tmp.first == n - 1) && (tmp.second == m - 1))
break;
for (int i = 0; i < 3; i++)
{
if ((tmp.first + go[i] >= 0) && (tmp.first + go[i] < m) && (maps[tmp.first+go[i]][tmp.second]) && visited[tmp.first + go[i]][tmp.second] == 0)
{
q.push(make_pair(tmp.first+go[i], tmp.second));
visited[tmp.first + go[i]][tmp.second] = visited[tmp.first][tmp.second] + 1;
}
if ((tmp.second + go[i] >= 0) && (tmp.second + go[i] < m) && (maps[tmp.first][tmp.second+go[i]]) && visited[tmp.first][tmp.second+go[i]] == 0)
{
q.push(make_pair(tmp.first, tmp.second + go[i]));
visited[tmp.first][tmp.second+go[i]] = visited[tmp.first][tmp.second] + 1;
}
}
}
return visited[n-1][m-1];
}
if ((tmp.first + go[i] >= 0) && (tmp.first + go[i] < n) && (maps[tmp.first+go[i]][tmp.second]) && visited[tmp.first + go[i]][tmp.second] == 0)
아무리 생각해도 틀릴 곳이 보이지 않음. 그럼 -1 예외상황 문제가 아닐까?
=> 만약 마지막 visited[n-1][m-1] == 0이면 -1을 추가로 넣어줌.
최종 코드
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
int solution(vector<vector<int> > maps)
{
int answer = 0;
int n = maps.size();
int m = maps[0].size();
int go[2] = {-1, 1};
int **visited = new int*[n];
queue<pair<int, int>> q;
for (int i = 0; i < n; i++)
visited[i] = new int[m]();
if ((maps[n - 1][m - 2] == 0) && (maps[n - 2][m - 1] == 0))
return -1;
q.push(make_pair(0,0));
visited[0][0] = 1;
pair<int, int> tmp;
while (q.size())
{
tmp = q.front();
q.pop();
if ((tmp.first == n - 1) && (tmp.second == m - 1))
break;
for (int i = 0; i < 2; i++)
{
if ((tmp.first + go[i] >= 0) && (tmp.first + go[i] < n) && (maps[tmp.first+go[i]][tmp.second]) && visited[tmp.first + go[i]][tmp.second] == 0)
{
q.push(make_pair(tmp.first+go[i], tmp.second));
visited[tmp.first + go[i]][tmp.second] = visited[tmp.first][tmp.second] + 1;
}
if ((tmp.second + go[i] >= 0) && (tmp.second + go[i] < m) && (maps[tmp.first][tmp.second+go[i]]) && visited[tmp.first][tmp.second+go[i]] == 0)
{
q.push(make_pair(tmp.first, tmp.second + go[i]));
visited[tmp.first][tmp.second+go[i]] = visited[tmp.first][tmp.second] + 1;
}
}
}
if (visited[n-1][m-1] == 0)
return -1;
else
return visited[n-1][m-1];
}
한가지 중요한 점은, 각 위치마다 최소값을 저장하고 있다는 점.if ((maps[n - 1][m - 2] == 0) && (maps[n - 2][m - 1] == 0)) return -1;
이 코드에서는 바로 주변이 막혀있는 경우만 판단. 없어도 정답이지만, 이 경우에는 불필요하게 while을 돌 필요가 없으므로 남겨둠.
while(q.size()) { ... }
bfs를 시작함.
0과 n-1사이 또는 0과 m-1사이인지 체크하고, 벽이 아니면서 방문된 상태인지 판단.
모든 조건을 만족하는 경우 queue에 넣고 방문처리.
모든 큐에 있는 값들이 없어지거나, 도착지에 도착하면 종료!