矩阵距离
题目告知01矩阵求解各个点到1点的最短距离
- bfs题目,还是预先定义方向数组
- 值得记录的就是
queue<pair<int,int> >
的使用方法q.push(make_pair(int_first,int_second))
- 直接使用pair时
pair<int int> now(int_first,int_second)
#include<bits/stdc++.h>
using namespace std;
int n,m,d[1005][1005];
char M[1005][1005];
queue<pair<int,int> >q;
const int dx[4] = {-1,1,0,0},dy[4] = {0,0,-1,1};
int main(){
cin>>n>>m;
memset(d,-1,sizeof(d));
for(int i = 1; i <= n; i++){
scanf("%s", M[i] + 1);
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(M[i][j]=='1'){
q.push(make_pair(i,j)),
d[i][j] = 0;
}
}
}
while(q.size()){
pair<int, int> now = q.front();
q.pop();
for(int k = 0;k<4;k++){
pair<int,int> next(now.first+dx[k],now.second+dy[k]);
if(next.first<1||next.second<1||next.first>n||next.second>m)
continue;
if(d[next.first][next.second]==-1){
d[next.first][next.second] = d[now.first][now.second] + 1;
q.push(next);
}
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cout << d[i][j]<<' ';
}
cout<<endl;
}
return 0;
}