图的遍历(深度递归遍历,深度非递归遍历,广度递归遍历)

最近在学数据结构,看到图的遍历小有疑惑,便去实现了一番。。。。

以下是用C++ 实现:


#include
#include    //队列定义,用于广度递归查询
#include   //栈的定义, 用于深度非递归查询
#include
#include    //方便调用c语言函数
#define MAX 100    //最大值

using namespace std ;

typedef struct
{
    int edges[MAX][MAX];
    int n;
    int e;
}MGraph;   //图的定义

bool visited[MAX];

void craeteMGraph (MGraph & G)   //初始化图
{
    int i, j;
    int s, t;
    int v;
    for (i = 0 ; i < G. n ; i ++ )   //将边清空
    {
        for (j = 0 ; j < G. n ; j ++ )
        {
            G. edges [i][j] = 0 ;
        }
        visited[i] = false ;
    }

    for (i = 0 ; i < G. e ; i ++ )  // 输入边和其对应的权值
    {
        scanf ( "%d %d %d" , & s, & t, & v);
        G. edges [s][t] = v;
    }
}

void DFS (MGraph G, int v)  //深度递归查询
{
    int i;
    printf ( "%d " , v);
    visited[v] = true ;
    for (i = 0 ; i < G. n ; i ++ )
    {
        if (G. edges [v][i] != 0 && visited[i] == false )
        {
            DFS (G, i);
        }
    }
}

void DFS1 (MGraph G, int v)  //深度非递归查询
{
    stack < int > s;
    printf ( "%d " , v);
    visited[v] = true ;
    s. push (v);
    while ( ! s. empty ())
    {
        int i, j;
        i = s. top ();
        for (j = 0 ; j < G. n ; j ++ )
        {
            if (G. edges [i][j] != 0 && visited[j] == false )
            {
                printf ( "%d " , j);
                visited[j] = true ;
                s. push (j);
                break ;
            }
        }
        if (j == G. n )
            s. pop ();
    }
}

void BFS (MGraph G, int v)  //广度查询
{
    queue < int > Q;
    printf ( "%d " , v);
    visited[v] = true ;
    Q. push (v);
    while ( ! Q. empty ())
    {
        int i, j;
        i = Q. front ();
        Q. pop ();
        for (j = 0 ; j < G. n ; j ++ )
        {
            if (G. edges [i][j] != 0 && visited[j] == false )
            {
                printf ( "%d " , j);
                visited[j] = true ;
                Q. push (j);
            }
        }
    }
}

int main ()
{
    int n, e;
    while ( scanf ( "%d %d" , & n, & e) == 2 && n > 0 )
    {
        MGraph G;
        G. n = n;
        G. e = e;
        craeteMGraph (G);
        //DFS(G, 0);
        //DFS1(G, 0);
        BFS (G, 0 );
        printf ( "\n" );
    }
}

/*  参考输入:
8 9
0 1 1
0 2 1
1 3 1
1 4 1
2 5 1
2 6 1
3 7 1
4 7 1
5 6 1

深度递归结果:0 1 3 7 4 2 5 6
深度非递归结果:0 1 3 7 4 2 5 6
广度递归结果: 0 1 2 3 4 5 6 7
*/

如有不对 欢迎指出

你可能感兴趣的:(基础)