当前位置:   article > 正文

多源BFS-- 矩阵距离

多源bfs

 

关于多源BFS,基本上就是单源BFS的简单升级了一下,比如在queue中队头开始时只有一个,我们通过这一个队头去推导其他的东西。而多源最短路就是队头一开始有1-n个可能的数,一个一个去BFS。

题目思路:

        这个题就直接把所有的1统计出来放进queue中,每次取出对头进行BFS即可,其中有两个问题:

1.我们BFS如何去找到他是0点,怎么通过0传递到下一个0。

2.如何保证他是最小值,会不会出现值覆盖的现象。

其实第一个问题我们可以直接用dist数组进行标记,一旦有0被靠近的1标记了,那么他自身我们就可以看作是个1,通过这个1我们再去找到下一个0。

第二个问题,不会出现覆盖,因为我们每次赋值之后dist就会变成附近1的dist值加1,dist!=-1(我们初始默认0的dist数组值为-1),我们每次都是取最近的,所以一旦到这个地方,其他的点就无法访问了,一旦访问便是最近距离。

千万别忘了判断数组是否越界,否则会导致段错误

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. char g[1010][1010];
  4. int n,m;
  5. int dist[1010][1010];
  6. typedef pair<int,int> PII;
  7. int dx[4]={1,0,-1,0};
  8. int dy[4]={0,-1,0,1};
  9. void bfs()
  10. {
  11. memset(dist,-1,sizeof(dist));
  12. queue<PII> q;
  13. for(int i=1;i<=n;i++)
  14. {
  15. for(int j=1;j<=m;j++)
  16. {
  17. if(g[i][j]=='1')
  18. {
  19. q.push({i,j});
  20. dist[i][j]=0;
  21. }
  22. }
  23. }
  24. while(q.size())
  25. {
  26. auto t=q.front();
  27. q.pop();
  28. for(int i=0;i<4;i++){
  29. int x=t.first+dx[i];
  30. int y=t.second+dy[i];
  31. if(x<1||x>n||y<1||y>m)
  32. continue;
  33. if(dist[x][y]!=-1)
  34. {
  35. continue;
  36. }
  37. else
  38. {
  39. dist[x][y]=dist[t.first][t.second]+1;
  40. q.push({x,y});
  41. }
  42. }
  43. }
  44. }
  45. int main()
  46. {
  47. cin>>n>>m;
  48. for(int i=1;i<=n;i++)
  49. {
  50. for(int j=1;j<=m;j++)
  51. {
  52. cin>>g[i][j];
  53. }
  54. }
  55. bfs();
  56. for(int i=1;i<=n;i++)
  57. {
  58. for(int j=1;j<=m;j++)
  59. {
  60. cout<<dist[i][j]<<" ";
  61. }
  62. cout<<endl;
  63. }
  64. return 0;
  65. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/781474
推荐阅读
相关标签
  

闽ICP备14008679号