-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path图_深度优先遍历_图连通_DFS_.cpp
132 lines (105 loc) · 2.19 KB
/
图_深度优先遍历_图连通_DFS_.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include<stdio.h>
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
#define Max_vexs 25
#define status int
#define Max_type -1
typedef struct
{
status arcs[Max_vexs][Max_vexs];
status vexnum,arcnum;
}graph;
status createUDG(graph *G)
{
int i,j,w;
printf("辺と点の数量を輸入してください:\n");
scanf("%d %d",&G->vexnum,&G->arcnum);
for(i=1;i<G->vexnum+1;i++)
{
for(j=1;j<G->vexnum+1;j++)
{
if(i==j)
{
G->arcs[i][j]= 0;
}
else
{
G->arcs[i][j]= Max_type;
}
}
}
cout<<"请输入边(vi, vj)和权值w,三个变量空格分隔即可:"<<endl;
for(int k=1;k<G->arcnum+1;k++)
{
cin>>i>>j>>w;
G->arcs[i][j]=w;
}
}
status printUDG(graph *G)
{
int i,j;
printf("辺と点の数量を輸出します:\n");
printf("%d %d\n",G->vexnum,G->arcnum);
printf("全て点の連絡の数字を輸出します:\n");
for(i=1;i<G->vexnum+1;i++)
{
for(j=1;j<G->vexnum+1;j++)
{
printf("%5d",G->arcs[i][j]);
}
printf("\n");
}
}
void Graph_Dfs(graph M, int visiting_Node)
{
int isVisited[M.vexnum+1]={0};
int visited_count=0;//记录已经访问过的节点
stack<int> p;
while(visited_count<M.vexnum)
{
if(isVisited[visiting_Node]==0)
{
cout<<"--->"<<visiting_Node<<" \n";
visited_count++;
}
p.push(visiting_Node);
isVisited[visiting_Node]=1;
int j;
for(j=1;j<M.vexnum+1;j++)
{
if(M.arcs[visiting_Node][j]!=0 && isVisited[j]==0 && M.arcs[visiting_Node][j]!=Max_type )
{
break;
}
}
if(j==M.vexnum+1)
{
p.pop();
if(!p.empty())
{
visiting_Node=p.top();
//cout<<"---+"<<visiting_Node<<" \n";
p.pop();//出队2次,原因上层的节点会再次入队
}
else
{
break;
}
}
else
{
visiting_Node=j;
}
}
}
int main()
{
graph gh;
createUDG(&gh);
printUDG(&gh);
cout<<"\n该图的深度遍历为:\n"<<endl;
Graph_Dfs(gh,1);
return 0;
}