Coding Test - cpp/BFS
[백준 2178 : 미로 탐색] - C++
에드윈H
2021. 1. 13. 09:48
#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
int n,m;
vector<int> map[100];
int dis[100][100];
bool check[100][100];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int main() {
memset(dis, 0, sizeof(dis));
memset(check, false, sizeof(check));
cin >> n>>m;
string num;
for (int i = 0; i < n; i++)
{
cin >> num;
for (int j = 0; j < m; j++)
{
int a = num[j] - '0';
map[i].push_back(a);
}
}
queue<pair<int, int>> Q;
Q.push({ 0, 0 });
map[0][0] = 0;
dis[0][0] = 1;
while (!Q.empty())
{
int xx = Q.front().first;
int yy = Q.front().second;
Q.pop();
for (int i = 0; i < 4; i++)
{
int nextX = xx + dx[i];
int nextY = yy + dy[i];
if(nextY<0 || m<=nextY || nextX<0 ||n<=nextX)
{
continue;
}
if (map[nextX][nextY] == 1 && !check[nextX][nextY])
{
check[nextX][nextY] = true;
Q.push({ nextX,nextY });
dis[nextX][nextY] = dis[xx][yy] + 1;
}
}
}
cout << dis[n - 1][m - 1] << endl;
return 0;
}