深度优先搜索

#include<iostream>
using namespace std;

#define Inf 65535
#define NotAVerter -1

int time = 0; //全局变量

/////////////////////邻接链表的相关定义//////////////////////
typedef struct EdgeNode *position;
typedef struct Led_table* Table;


struct EdgeNode     //边表结点 
{
	int adjvex;    // 邻接点域,存储该顶点对应的下标 
	int color;    //此标志表示对应的节点是否已经搜索到,0为白色,1为灰色,2为黑色
	int t_start;
	int t_finish;
	int precursor;  //此数据记录该节点在广度优先树种的前驱节点
	position next; // 链域,指向下一个邻接点
};

struct Led_table       // 邻接表结构 
{
	int data;                //邻接表的大小
	position *firstedge;       //边表头指针,可以理解为数组
};


//////////////////////////邻接链表相关函数定义///////////////
Table Creat_Lable(int MaxElements)    //MaxElements参数为希望创建的节点数
{

	Table table1 = static_cast<Table> (malloc(sizeof(struct Led_table)));
	table1->data = MaxElements;
	if (table1 == NULL)
	{
		cout << "out of space!!!";
	}

	table1->firstedge = static_cast<position*>(malloc(sizeof(position)*(table1->data)));
	if (table1->firstedge == NULL)
	{
		cout << "out of space!!!";
	}

	//给每个表头赋值,从0开始
	for (int i = 0; i <= table1->data - 1; ++i)
	{
		table1->firstedge[i] = static_cast<position>(malloc(sizeof(EdgeNode)));   //申请一个节点
		if (table1->firstedge[i] == NULL)
		{
			cout << "out of space!!!";
		}
		table1->firstedge[i]->adjvex = 0;   //表头这个参数没有意义
    	table1->firstedge[i]->color = 0;    //全部设置为白色
		table1->firstedge[i]->t_start = 0;
		table1->firstedge[i]->t_finish = 0;
		table1->firstedge[i]->precursor = NotAVerter;
		table1->firstedge[i]->next = NULL;

	}
	return table1;

}


void Insert(Table table1, int v, int w)   //表示存在一条边为<v,w>
{
	position p = static_cast<position>(malloc(sizeof(EdgeNode)));   //申请一个节点
	if (p == NULL)
	{
		cout << "out of space!!!";
	}
	p->adjvex = w;
	p->color = 0;    //对于普通节点来说无意义
	p->t_finish = 0;
	p->t_start = 0;
	p->precursor = NotAVerter;  //对于普通节点来说无意义
	p->next = table1->firstedge[v]->next;
	table1->firstedge[v]->next = p;


}



/////////////////////////////////深度优先搜索算法/////////////////////////////////
void Dfs_Visit(Table table1, int u)
{
	time = time + 1;
	table1->firstedge[u]->t_start = time;
	table1->firstedge[u]->color = 1;

	position p = table1->firstedge[u]->next;
	while (p != NULL)
	{
		if (table1->firstedge[p->adjvex]->color == 0)
		{
			
			table1->firstedge[p->adjvex]->precursor = u;
			Dfs_Visit(table1, p->adjvex);
		}
		p = p->next;
	}
	table1->firstedge[u]->color = 2;
	time++;
	table1->firstedge[u]->t_finish = time;
}




int main()
{
	Table table_1 = Creat_Lable(6);    //创建一个大小为8的邻接表

	Insert(table_1, 0, 1); Insert(table_1, 0, 3);
	Insert(table_1, 1, 4);
	Insert(table_1, 2, 5);
	Insert(table_1, 3, 1); 
	Insert(table_1, 4, 3); Insert(table_1, 4, 2);
	Insert(table_1, 5, 5); 

	Dfs_Visit(table_1, 0);

	for (int i = 0; i <= table_1->data - 1; ++i)
	{
		cout << "结点" << i << "的起始时间为" << table_1->firstedge[i]->t_start
			<< "结束时间为" << table_1->firstedge[i]->t_finish << endl;
	}
		
	

	return 0;
}

  夜深了。

posted on 2017-09-24 16:59  wu_xin  阅读(150)  评论(0编辑  收藏  举报

导航