深度優先搜索

深度優先搜索算法:

#ifndef DFS_H
#define DFS_H


#include <iostream>
#include "stdio.h"
#include <list>

using namespace std;

#define NUM 6

typedef struct _stNode 
{
	char syb;
}stNode;


stNode nodeAry[NUM];
int color[NUM];a
stNode *par[NUM];

list<stNode *> graph[NUM];
list<stNode *>::iterator itrList;

void create();
void dfs();
void dfs_visit(stNode *node);
stNode *getNode(int i);
int getNodeIndex(stNode *node);

void getSysTime(time_t &time);

#endif
#include "dfs.h"


void create()
{
	int i = 0;
	for(i = 0; i < NUM; i++)
	{
		nodeAry[i].syb = 'u' + i;
	}
	
	for(i = 0; i < NUM; i++)
	{
		color[i] = 0;
		par[i] = NULL;
	}
	graph[0].push_back(&nodeAry[0]);
	graph[0].push_back(&nodeAry[1]);
	graph[0].push_back(&nodeAry[3]);
	
	graph[1].push_back(&nodeAry[1]);
	graph[1].push_back(&nodeAry[4]);

	graph[2].push_back(&nodeAry[2]);
	graph[2].push_back(&nodeAry[4]);
	graph[2].push_back(&nodeAry[5]);

	graph[3].push_back(&nodeAry[3]);
	graph[3].push_back(&nodeAry[1]);

	graph[4].push_back(&nodeAry[4]);
	graph[4].push_back(&nodeAry[3]);

	graph[5].push_back(&nodeAry[5]);
	graph[5].push_back(&nodeAry[5]);

}


stNode *getNode(int i)
{
	int j = 0;
	for(j = 0; j < NUM; j++)
	{
		if(i == (nodeAry[j].syb - 'u'))
		{
			break;
		}
	}
	return &nodeAry[j];
}

int getNodeIndex(stNode *node)
{
	return (node->syb - 'u');
}

void dfs()
{
	int j = 0;
	stNode *node;
	for(j = 0; j < NUM; j++)
	{
		if(color[j] == 0)
		{
			dfs_visit(getNode(j));
			printf("j = %d\n", j);
		}
	}
}

void dfs_visit(stNode *node)
{
	int parI = getNodeIndex(node);
	int childI = 0;
	color[parI] = 1;
	int i = 0;
/*
	for(itrList = graph[parI].begin(); itrList != graph[parI].end(); ++itrList)
	{
		childI = getNodeIndex(*itrList);
		printf("p = %c, c = %c\n", node->syb, (*itrList)->syb);
		if(0 == color[childI])
		{
			par[childI] = node;
			dfs_visit(*itrList);
		}
	}
*/
	stNode *cNode = 0;
	while(!graph[parI].empty())
	{
		cNode = graph[parI].front();
		childI = getNodeIndex(cNode);
		if(0 == color[childI])
		{
			par[childI] = node;
			dfs_visit(cNode);
		}
		graph[parI].remove(cNode);
	}		
	color[parI] = 2;
}



int main()
{
	create();
	int i = 0;
	dfs();
}

註釋部分使用了list的迭代器,但是會出現錯誤:Error list iterator not incrementable

,這可能是由於迭代器在遞歸回退後使迭代器無法迭代。所以進行了修改。

点赞