DFS - 深度搜索 - 基于邻接列表表示法

2017-07-25 15:38:00

writer:pprp

在前一篇图基于邻接列表表示法的代码加了一小部分,加了一个DFS函数,visited[N]数组

参考书目:张新华的《算法竞赛宝典》


 

代码如下:

#include <iostream>

using namespace std;

const int N = 9;

int visited[N] = {0};    //新引入一个数组,用于标记是否访问过

struct node
{
    int vertex;
    node*next;
};

node head[N];
void create(int node1,int node2)//通过起点和终点的值创建一个邻接表
{
    node * point;
    node * New = new node();
    if(New!=NULL)
    {
        New->vertex = node2;
        New->next = NULL;
        point = &(head[node1]);
        while(point->next!=NULL)
            point = point->next;
        point->next = New;
    }
}

void DFS(int vertex)
{
    node*point;
    visited[vertex] = 1;
    cout <<"["<<vertex<<"]->";
    point  = head[vertex].next;
    while(point!=NULL)
    {
         if(visited[point->vertex]==0)
            DFS(point->vertex);
         point = point->next;
    }
}

void print()
{
    node*point;
    for(int i = 0; i < N; i++)
    {
        point = head[i].next;
        cout << "Head["<<i<<"]";
        while(point!=NULL)
        {
            cout <<"-> "<<point->vertex;
            point = point->next;
        }
        cout << endl;
    }
}

int main()
{
    int node1,node2;
    
    for(int i = 0; i < N; i++)
    {
        head[i].vertex = i;
        head[i].next = NULL;
    }
    while(1)
    {
        cout <<"please enter the start point" << endl;

        cin >> node1;
        if(node1 == -1)
            break;
        cout <<"please enter the end point" << endl;
        cin >> node2;

        if(node1 == node2)
            cout <<"自身循环"<<endl;
        else if(node1>=N||node2>=N)
            cout <<"超出范围"<<endl;
        else
            create(node1,node2);
    }

    cout << "邻接表为:" << endl;
    print();
    
    DFS(1);
    
    cout <<"\n"<<endl;

    return 0;
}

 

posted @ 2017-07-25 15:41  pprp  阅读(251)  评论(0编辑  收藏  举报