[ 문제 ]
14940번: 쉬운 최단거리
지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000) 다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이
www.acmicpc.net
[ 접근방법 ]
목표지점을 시작점으로 하여 BFS를 돌린다.
[ 소스코드 ]
#include <iostream>
#include <queue>
using namespace std;
int n, m, a, b;
int map[1005][1005];
int ans[1005][1005];
bool chk[1005][1005];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
queue<pair<int, int>> q;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> map[i][j];
if (map[i][j] == 2)
{
a = i;
b = j;
}
if (map[i][j] == 1)
ans[i][j] = -1;
}
}
chk[a][b] = true;
q.push({a, b});
while (!q.empty())
{
pair<int, int> qf = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
pair<int, int> np = {qf.first + dx[i], qf.second + dy[i]};
if (np.first < 0 || np.first >= n || np.second < 0 || np.second >= m)
continue;
if (!map[np.first][np.second])
continue;
if (chk[np.first][np.second])
continue;
ans[np.first][np.second] = ans[qf.first][qf.second] + 1;
chk[np.first][np.second] = true;
q.push(np);
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << ans[i][j] << " ";
}
cout << "\n";
}
return 0;
}
'PS' 카테고리의 다른 글
[ 백준 / C++ ] 1715 : 카드 정렬하기 (0) | 2024.04.29 |
---|---|
[ 백준 / C++ ] 15686 : 치킨 배달 (0) | 2024.04.26 |
[ 백준 / C++ ] 11779 : 최소비용 구하기 2 (0) | 2024.04.24 |
[ 백준 / C++ ] 1915 : 가장 큰 정사각형 (0) | 2024.04.23 |
[ 백준 / C++ ] 8979 : 올림픽 (0) | 2024.04.22 |