0%

图的邻接矩阵遍历

图的邻接矩阵遍历

以下为数据结构作业
如有错误,请指出,谢谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<bits/stdc++.h>
using namespace std;
int m[100][100],vis[100],N;
void DFS_1(int n)
{
if(vis[n])return;
else
{
cout<<" -> "<<n;
vis[n]=1;
for(int i=0;i<N;i++)
if(m[n][i]&&!vis[i])DFS_1(i);
}
}
void DFS_2(int n)
{
stack<int>S;
vis[n]=1;
S.push(n);
while(!S.empty())
{
int t=S.top();
cout<<" -> "<<t;
S.pop();
for(int i=N-1;i>=0;i--)
{
if(m[t][i]&&!vis[i])
{
S.push(i);
vis[i]=1;
}
}
}
}
void BFS(int n)
{
queue<int>Q;
Q.push(n);
vis[n]=1;
while(!Q.empty())
{
int t=Q.front();
Q.pop();
cout<<" -> "<<t;
for(int i=0;i<N;i++)
if(m[t][i]&&!vis[i])
{
Q.push(i);
vis[i]=1;
}
}
}
int main()
{
int a,b,ch;
cin>>N;
for(int i=1;i<=N;i++)
{
cin>>a>>b;
m[a][b]=1;
m[b][a]=1;
}
while(cin>>ch)
{
memset(vis,0,sizeof(vis));
if(ch==1)DFS_1(0);
else if(ch==2)DFS_2(0);
else if(ch==3)BFS(0);
else break;
cout<<endl;
}
return 0;
}

赏点呗!