您的位置:首页 > 其它

DFS算法的实现

2012-05-12 12:23 561 查看
#graph.h头文件

#ifndef GRAPH_H
#define GRAPH_H

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

/*图的矩阵表示向邻接表表示的转换*/
void matrixToAdjlist(int *matrix, adjNode *adjList, int n){
int i, j;
adjNode *tempNode;
for(i=0; i<n; ++i){
adjList[i].node=i;
adjList[i].next=NULL;

for(j=n-1; j>=0; j--){
if(*(matrix+i*n+j)== 1){
tempNode=(adjNode *)malloc(sizeof(adjNode));
tempNode->next=adjList[i].next;
tempNode->node=j;
adjList[i].next=tempNode;
}
}
}
}

/*释放邻接表中分配的空间*/
void freeAdjList(adjNode *adjList, int n){
int i;
adjNode *tempNode;

for(i=0; i<n; ++i){
tempNode=adjList[i].next;
while(tempNode != NULL){
adjList[i].next=tempNode->next;
free(tempNode);
tempNode=adjList[i].next;
}
}

free(adjList);
}

#endif // GRAPH_H


main.h

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "graph.h"
using namespace std;

const int invalid_p=-1;
int gtm=0;
enum Color{w, g, b};

struct DFS_struct{
Color color;
int parent;
int dtime, ftime;  //节点的发现时间和邻接表扫描完成时间
};

void DFS_visit(adjNode *adjList, DFS_struct *dfsArray, int u){
int v;
adjNode *tempNode;

dfsArray[u].color=g;
gtm += 1;
dfsArray[u].dtime=gtm;

tempNode=adjList[u].next;
while(tempNode != NULL){
v=tempNode->node;
if(dfsArray[v].color == w){
dfsArray[v].parent=u;
DFS_visit(adjList, dfsArray, v);
}

tempNode=tempNode->next;
}

dfsArray[u].color=b;
gtm += 1;
dfsArray[u].ftime=gtm;
}

void DFS(adjNode *adjList, DFS_struct *dfsArray, int n, vector<int> &forestRoots){
int i;
for(i=0; i<n; ++i){
dfsArray[i].color=w;
dfsArray[i].parent=invalid_p;
dfsArray[i].dtime=0;
dfsArray[i].ftime=0;
}

gtm=0;
for(i=0; i<n; ++i)
if(dfsArray[i].color == w){
DFS_visit(adjList, dfsArray, i);    //每次调用都会生成一棵深度优先搜索树,最终生成深度优先搜索森林
forestRoots.push_back(i);
}
}

int main(){
int *matrix;
adjNode *adjList, *tempNode;
int nodeNum=0, i, j;
DFS_struct *dfsArray;
vector<int> forestRoots;        //forestRoots中保存每棵深度优先搜索树的树根节点编号

printf("Input node number: ");
scanf("%d", &nodeNum);

matrix=(int *)malloc(sizeof(int)*nodeNum*nodeNum);
adjList=(adjNode *)malloc(sizeof(adjNode)*nodeNum);

for(i=0; i<nodeNum; ++i)
for(j=0; j<nodeNum; ++j)
scanf("%d", matrix+i*nodeNum+j);

/*以矩阵形式输出图*/
printf("matrix: \n");
for(i=0; i<nodeNum; ++i){
for(j=0; j<nodeNum; ++j)
printf("%d ", *(matrix+i*nodeNum+j));
printf("\n");
}

matrixToAdjlist(matrix, adjList, nodeNum);
/*以邻接表形式输出图*/
printf("adjacency list: \n");
for(i=0; i<nodeNum; ++i){
printf("node %d:", adjList[i].node);
tempNode=adjList[i].next;
while(tempNode != NULL){
printf("->%d", tempNode->node);
tempNode=tempNode->next;
}
printf("\n");
}

dfsArray=(DFS_struct *)malloc(sizeof(DFS_struct)*nodeNum);
DFS(adjList, dfsArray, nodeNum, forestRoots);

/*在这里深度优先搜索森林已经建立,可以进行别的操作*/
printf("DFS learning completed\n");
printf("forest roots:");
for(i=0; i<forestRoots.size(); ++i)
printf("%d ", forestRoots[i]);
printf("\n");

free(matrix);
free(dfsArray);
freeAdjList(adjList, nodeNum);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: