목표지점 까지의 거리 = 목표지점에서 각 지점까지의 거리임을 생각해내면 쉬운 문제.
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> board(n+1, vector<int>(m+1));
queue<pii> Q;
vector<vector<int>> dist(n+1, vector<int>(m+1, -1));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cin >> board[i][j];
if (board[i][j] == 1) continue;
if (board[i][j] == 2) Q.push({i, j});
dist[i][j] = 0;
}
}
while (Q.size()) {
int nowX = Q.front().first;
int nowY = Q.front().second;
Q.pop();
for (int i = 0; i < 4; ++i) {
int nextX = nowX + dx[i];
int nextY = nowY + dy[i];
if (nextX < 1 || nextX > n || nextY < 1 || nextY > m) continue;
if (dist[nextX][nextY] != -1) continue;
dist[nextX][nextY] = dist[nowX][nowY] + 1;
Q.push({nextX, nextY});
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cout << dist[i][j] << ' ';
}
cout << '\n';
}
}