深度优先搜索

来源:互联网 发布:淘宝互刷代付骗局 编辑:程序博客网 时间:2024/06/06 03:34

此深度优先搜索是针对于有向图的,在实现中并未构造深度搜索树。即不使用树来实现对有向图的深度优先搜索。
下面是MapInfo.txt文件中的内容,此文件保存着有向图的邻接矩阵。
0 1 0 1 0 0
0 0 0 0 1 0
0 0 0 0 1 1
0 1 0 0 0 0
0 0 0 1 0 0
0 0 0 0 0 1
程序会先读取此邻接矩阵的内容,然后构建一个邻接表,最后在邻接表上实现对此有向图的深度优先搜索。
代码实现如下:

/* * 深度优先搜索 * 有向图 不构建深度搜索树 *           Author: StoryMonster * last change date: 2016/6/30 */#include <iostream>#include <stdio.h>#include <stdlib.h>enum {White,Grey,Black};typedef struct MapNode{    int NodeName;    int color;    struct MapNode *next;} MapNode;MapNode *Head[6];static void ReadConfigFile();static void InsertToMap(MapNode *, MapNode *);static void Deepth_First_Search(void);static void Search(MapNode *);void ColorAll(int NodeName, int color){    for(int i=0;i<6;i++)    {        MapNode *p = Head[i];        while(p!=NULL)        {            if(p->NodeName == NodeName)            {                p->color = color;            }            p = p->next;        }    }}MapNode *GetNode(int name){    for(int i=0;i<6;i++)    {        if(name == i+1)            return Head[i];    }}void Search(MapNode *root){    if(root == NULL) return ;    if(root->color == White)    {        root->color = Grey;        ColorAll(root->NodeName,Grey);        std::cout << root->NodeName << std::endl;    }    MapNode *p = root->next;    while(p!=NULL)    {        if(p->color == White)        {            p->color = Grey;            ColorAll(p->NodeName,Grey);            std::cout << p->NodeName << std::endl;            Search(GetNode(p->NodeName));        }        p = p->next;    }    root->color = Black;}void Deepth_First_Search(void){    for(int i=0;i<6;i++)    {        if(Head[i]->color == White)        {            Search(Head[i]);        }    }}void InsertToMap(MapNode *head, MapNode *node){    if(head == NULL)    {        head = node;        return ;    }    MapNode *p = head;    while(p->next != NULL) p = p->next;    p->next = node;}void ReadConfigFile(void){    FILE *fp = fopen("MapInfo.txt","rb");    if(!fp)    {        std::cout << "Open MapInfo.txt failed!" <<std::endl;        fp = NULL;        return ;    }    int index = 0;    int arr[6] = {0};    while(1)    {        int n = fscanf(fp,"%d %d %d %d %d %d",&arr[0],&arr[1],&arr[2],&arr[3],&arr[4],&arr[5]);        if(n < 1) break;        for(int i =0;i<6;i++)        {            if(arr[i])            {                MapNode *node =(MapNode *)malloc(sizeof(MapNode));                node->NodeName = i+1;                node->next     = NULL;                node->color    = White;                InsertToMap(Head[index],node);            }        }        index++;    }    fclose(fp);    fp = NULL;}int main(){    for(int i=0;i<6;i++)    {        Head[i] = (MapNode *)malloc(sizeof(MapNode));        Head[i]->next = NULL;        Head[i]->color= White;        Head[i]->NodeName = i+1;    }    ReadConfigFile();    Deepth_First_Search();    return 0;}

使用本代码实现对有向图的深度优先搜索当然在性能上比不上使用深度优先搜索树,因为在邻接表中为很多重复节点分配了内存。

1 0
原创粉丝点击