数据结构-图的遍历——BFS广度优先搜索

题目链接:https://www.dotcpp.com/oj/problem1703.html?sid=7509237&lang=1#editor

板子题,需要注意的是利用邻接矩阵存图,但是这样就变成了纯bfs模板,只要判断是否是走过并且这个点是否能走就可以了,

而对于图来说,尤其是利用邻接矩阵存图,0代表的是这条边不是图的边,1代表这条边是图的边,

而对于网图来讲,Gij代表的是这个图的边,并且是权值,而0或者是INF(无穷大)则代表不是图的边。

然后这个题就可以用bfs了:

Talk is cheap. Show me the code.

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int num=100;
 4 int n;
 5 int graph[num][num];//邻接矩阵
 6 bool vis[num];//标记数组
 7 void bfs(int s)
 8 {
 9     vis[s]=1;
10     queue<int>q;
11     q.push(s);//起点入队
12     cout<<0<<" ";//打印起点
13     while(!q.empty())
14     {
15         int x=q.front();
16         q.pop();
17         for(register int i=0;i<n;i++)
18         {
19             if(!vis[i]&&graph[x][i])//满足条件,并且当前点的邻居也满足条件
20             {
21                 vis[i]=1;//标记
22                 cout<<i<<" ";//打印这个点
23                 q.push(i);//这个点入队
24             }
25             else//如果不是就跳过
26             continue;
27         }
28     }
29 }
30 int main()
31 {
32     std::ios::sync_with_stdio(false);
33     cin>>n;
34     for(register int i=0;i<n;i++)
35     {
36         for(register int j=0;j<n;j++)
37         {
38             cin>>graph[i][j];
39         }
40     }
41     bfs(0);//从0开始搜
42     return 0;
43 }

 

posted @ 2022-04-29 15:33  江上舟摇  阅读(43)  评论(0编辑  收藏  举报