图的深度遍历过程不再此描述,本文描述的是实现。
递归实现
void dfs(int start){
visited[start] = 1;
cout << start << "->";
for(int i = 1;i<=vex_num;i++){
if(visited[i] == 0 && graph[start][i] == 1)
dfs(i);
}
}
非递归实现
stack<int>s;
void dfs(int start){
visited[start] = 1;
cout << start << "->";
s.push(start);
while(!s.empty()){
start = s.top();
int i;
for(i = 1;i <=vex_num ;i++){
if(visited[i] == 0 && graph[start][i] == 1){
cout << i << "->";
visited[i] = 1;
s.push(i);
break;
}
}
if(i == vex_num+1)
s.pop();
}
}
其中graph为一个二维数组,若无向图中两个顶点v1,v2有边,则graph[v1][v2]和graph[v2][v1]为1
原文链接: https://www.cnblogs.com/outxiao/p/13720176.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/203187
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!