图的深搜和广搜

 

 

#include<iostream>
#include<queue>
using namespace std;
#define VERTEX_MAX 20


bool visted[VERTEX_MAX];

typedef struct node {
    int adjvex;                         //顶点的位置
    struct node * next;             //指向下一条边的指针
}EdgeNode;

typedef struct vnode {
    char vertex;
    EdgeNode *firstedge;
}AdjList[VERTEX_MAX];

typedef struct {
    AdjList vertexs;                    //邻接表
    int verNum, edgeNum;            //图中顶点和边的数量
}Graph;

/*****************************************************
*
*        建立图的邻接表
*
******************************************************/

void CreateGraph(Graph *G) {
    int v1, v2, i, j, k;
    cout<<"请输入图的顶点数n和边数e:"<<endl;
    cin>>G->verNum>>G->edgeNum;
    cout<<"请输入每个顶点的编号"<<endl;

    for( i = 0; i < G->verNum; i++)
    {
        cin>>G->vertexs[i].vertex;
        G->vertexs[i].firstedge = NULL;
    }
    cout<<"请输入每条边对应的顶点:"<<endl;
    EdgeNode *p;
    for(k = 0; k < G->edgeNum; k++)
    {
        cin>>i>>j;
        p = new node;
        p->adjvex = j - 1;
        p->next = G->vertexs[i - 1].firstedge;
        G->vertexs[i - 1].firstedge = p;
    }

}
/****************************************************
*
* 深搜
*
*****************************************************/

void DFSTraverse(Graph *G, int v)
{
    visted[v] = true;
    cout<<G->vertexs[v].vertex<<"->";
    EdgeNode *p =  G->vertexs[v].firstedge;
    while( p != NULL)
    {
        if(!visted[p->adjvex])
        {
            DFSTraverse(G, p->adjvex);
        }
        p = p->next;
    }
}

void DFS(Graph *G)
{
    for(int i = 0; i < G->verNum; i++)
    {
        visted[i] = false;
    }
    cout<<"深搜:";
    for(int i = 0; i < G->verNum; i++)
    {
        if(!visted[i])
        {
            DFSTraverse(G, i);
        }
    }
    cout<<"null\n";
}

/**************************************************
*
* 广搜
*
**************************************************/

void BFS(Graph *G)
{
    queue<int > q;
    EdgeNode *p;
    for(int i = 0; i < G->verNum; i++)
    {
        visted[i] = false;
    }
    cout<<"广搜: ";
    for(int i = 0; i < G->verNum; i++)
    {
        if(!visted[i])
        {
            visted[i] = true;
            cout<<G->vertexs[i].vertex<<"->";
            q.push(i);
            while(!q.empty())
            {
                int j = q.front();
                q.pop();
                p = G->vertexs[j].firstedge;
                while(p)
                {
                    if(!visted[p->adjvex])
                    {
                        cout<<G->vertexs[p->adjvex].vertex<<"->";
                        visted[p->adjvex] = true;
                        q.push(p->adjvex);
                    }
                    p = p->next;
                }
            }
        }
    }
    cout<<"null\n";
}

int main()
{
    Graph *G = new Graph;
    CreateGraph(G);
    DFS(G);
    BFS(G);
    return 0;
}

  

posted on 2012-06-03 23:37  genslow  阅读(446)  评论(0编辑  收藏  举报