2021.11.04 bfs
题目名:矩阵距离
题目链接:https://www.acwing.com/problem/content/175/
思路:把所有的”1”入队,然后bfs就ok了
#include<bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
const int N = 1010;
int a[N][N], dist[N][N];
int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1};
int n, m;
queue<pii> q;
bool value(int x, int y){
return ~x && ~y && x < n && y < m;
}
int main(){
cin >> n >> m;
memset(dist, 0x3f, sizeof dist);
for(int i = 0; i < n; i++){
string s; cin >> s;
for(int j = 0; j < m; j++)
if(s[j] == '1') a[i][j] = 1, q.push({i,j}), dist[i][j] = 0;
}
while(q.size()){
int x = q.front().first, y = q.front().second;
q.pop();
for(int i = 0; i < 4; i++){
int nx = x + dx[i], ny = y + dy[i];
if(value(nx, ny) && dist[nx][ny] == 0x3f3f3f3f){
q.push({nx, ny});
dist[nx][ny] = dist[x][y] + 1;
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++)
cout << dist[i][j] << ' ';
cout << "\n";
}
return 0;
}