图的深度遍历和广度遍历(非递归C++实现)

深度遍历:栈实现的基本思路是将一个节点所有未被访问的“邻居”(即“一层邻居节点”)踹入栈中“待用”,然后围绕顶部节点猛攻,每个节点被访问后被踹出。

#include <iostream>
#include <stack>
using namespace std;

#define MaxNode 20
#define MAX 2000
#define StartNode 1

int map[MaxNode+1][MaxNode+1];

void dfs_stack(int start, int n){
    int visited[MaxNode],s_top;
    for(int i = 0;i <= MaxNode; i++){
        visited[i] = 0;
    }
    visited[start] = 1;
    stack <int> s;
    cout<<start<<" ";
    for(int i = 1; i <= n; i++){
        if(map[i][start] == 1 && !visited[i] ){
            visited[i] =  1;
            s.push(i);
        }
    }
    
    while(!s.empty()){
        s_top =  s.top();
        visited[s_top] = 1;
        cout<<s_top<<" ";
        s.pop();
        for(int i = 1; i <= n; i++){
            if(map[i][s_top] == 1 && !visited[i] ){
                visited[i] = 1;
                s.push(i);
            }
        }
    }
    
}

int main(int argc, const char * argv[]) {
    int num_edge,num_node;
    int x,y;
    cout<<"Input number of nodes and edges >"<<endl;
    cin>>num_node>>num_edge;
    for(int i =0;i<num_node;i++){
        for(int j=0;j<num_node;j++){
            map[i][j] = 0;
        }
    }
    for(int i = 1; i <= num_edge; i++){
        cin>>x>>y;
        map[x][y] = map[y][x] = 1;
    }
    
    dfs_stack(StartNode, num_node);

    return 0;
}

广度遍历:依靠队列实现,从给定的起点节点开始,依次将其邻接节点全部塞入队列,每次访问一个节点时将其pop()出队列,并将其邻接节点也塞入队列。直到队列为空,算法结束。

#include <iostream>
#include <queue>
using namespace std;

#define MAX 20
#define START 1

int visited[MAX];
int map[MAX][MAX];

void bfs(int start, int n){
    queue<int> q;
    int q_top;
    cout<<start<<" ";
    visited[start] = 1;
    for (int i = 1; i <= n ;i++ ) {
        if(map[start][i] == 1 && visited[i] == 0){
            q.push(i);
            visited[i] = 1;
        }
    }
    while(!q.empty()){
        q_top = q.front();
        q.pop();
        cout<<q_top<<" ";
        for(int i = 1; i <= n; i++ ){
            if(map[q_top][i] == 1 && visited[i] == 0){
                q.push(i);
                visited[i] = 1;
            }
        }
    }
    
}

int main(int argc, const char * argv[]) {
    int num_vex,num_edge,x,y;
    cout<<"Input number of nodes and edges >> ";
    cin>>num_vex>>num_edge;
    for(int i=0;i<MAX;i++){
        for(int j = 0;j < MAX;j++){
            map[i][j] = 0;
        }
    }
    for(int i = 1;i <= num_vex;i++){
        visited[i] = 0;
    }
    cout<<"Input edges, "<<num_edge<<" left >> ";
    for(int i = 1;i <= num_edge;i++){
        cin>>x>>y;
        map[x][y] = map[y][x] = 1;
        cout<<"Input edges, "<<(num_edge-i)<<" left >> ";
    }
    bfs(START, num_vex);
    return 0;
}

 

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/sinat_36412790/article/details/81945658
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞