CH2501矩阵距离(BFS)

12 篇文章 0 订阅
8 篇文章 0 订阅

矩阵距离
题目告知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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数学小牛马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值