[Silver / 14940] 쉬운 최단거리
🔷 분류
그래프 이론, 그래프 탐색, 너비 우선 탐색, 격자 그래프
✒️ 문제 설명
지도가 주어지면 모든 지점에 대해서 목표지점까지의 거리를 구하여라.
문제를 쉽게 만들기 위해 오직 가로와 세로로만 움직일 수 있다고 하자.
⬅️ 입력
지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000)
다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이다. 입력에서 2는 단 한개이다.
➡️ 출력
각 지점에서 목표지점까지의 거리를 출력한다. 원래 갈 수 없는 땅인 위치는 0을 출력하고, 원래 갈 수 있는 땅인 부분 중에서 도달할 수 없는 위치는 -1을 출력한다.
💻 코드 (C++)
#include <iostream>
#include <queue>
#include <utility>
using namespace std;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int map[1001][1001];
int dist[1001][1001];
bool vis[1001][1001];
queue<pair<int, int>> q;
void BFS(int x, int y) {
q.push({x, y});
vis[x][y] = true;
while(!q.empty()) {
auto now = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = now.first + dx[i];
int ny = now.second + dy[i];
if(nx < 0 || ny < 0 || nx > 1000 || ny > 1000) continue;
if(vis[nx][ny]) continue;
if(map[nx][ny] == 0) continue; // 이동 불가
else if(map[nx][ny] == 1 && !vis[nx][ny]) { // 이동 가능 & 방문 X 라면
q.push({nx, ny});
dist[nx][ny] = dist[now.first][now.second] + 1;
vis[nx][ny] = true;
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
int sx, sy;
cin >> n >> m;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int input;
cin >> input;
if(input == 2) {
sx = i; sy = j;
}
map[i][j] = input;
}
}
BFS(sx, sy);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(!vis[i][j] && map[i][j] == 1) cout << "-1 ";
else cout << dist[i][j] << " ";
}
cout << "\n";
}
return 0;
}
공유하기
Twitter Facebook LinkedIn글 이동
Comments