Init.h文件
#ifndef INIT
#include <stdio.h>
#include <stdlib.h>
constexpr auto MaxVertexNum = 100 ;
typedef int Ver;
typedef int WeigthType;
typedef int DataType;
typedef struct ENode {
Ver v1, v2;
WeigthType weigth;
} * PtrToENode;
typedef PtrToENode Edge;
typedef struct AdjVNode {
Ver AdjV;
WeigthType weight;
struct AdjVNode* Next;
} * PtrToAdjVNode;
typedef struct VNode {
PtrToAdjVNode FirstEdge;
DataType Data;
} AdjList[ MaxVertexNum] ;
typedef struct GNode {
int Nv;
int Ne;
AdjList G;
} * PtrToGNode;
typedef PtrToGNode LGraph;
void DFS ( LGraph Graph, Ver V) ;
LGraph BuildGraph ( ) ;
void InsertEdge ( LGraph Graph, Edge E) ;
#endif
DFS.CPP文件
#include "Init.h"
bool Visited[ MaxVertexNum] = { false } ;
LGraph CreatGraph ( int VertexNum)
{
Ver V;
LGraph Graph;
Graph = ( LGraph) malloc ( sizeof ( struct GNode) ) ;
Graph- > Nv = VertexNum;
Graph- > Ne = 0 ;
for ( V = 0 ; V < Graph- > Nv; V++ )
Graph- > G[ V] . FirstEdge = NULL ;
return Graph;
}
void InsertEdge ( LGraph Graph, Edge E)
{
PtrToAdjVNode newNode;
newNode = ( PtrToAdjVNode) malloc ( sizeof ( struct AdjVNode) ) ;
newNode- > AdjV = E- > v2;
newNode- > weight = E- > weigth;
newNode- > Next = Graph- > G[ E- > v1] . FirstEdge;
Graph- > G[ E- > v1] . FirstEdge = newNode;
newNode = ( PtrToAdjVNode) malloc ( sizeof ( struct AdjVNode) ) ;
newNode- > AdjV = E- > v1;
newNode- > weight = E- > weigth;
newNode- > Next = Graph- > G[ E- > v2] . FirstEdge;
Graph- > G[ E- > v2] . FirstEdge = newNode;
}
LGraph BuildGraph ( )
{
int Nv, i;
Ver V;
Edge E;
LGraph Graph;
printf_s ( "请输入插入节点的个数\n" ) ;
scanf_s ( "%d" , & Nv) ;
Graph = CreatGraph ( Nv) ;
printf_s ( "请输入插入边的个数\n" ) ;
scanf_s ( "%d" , & ( Graph- > Ne) ) ;
if ( Graph- > Ne != 0 )
{
E = ( Edge) malloc ( sizeof ( struct ENode) ) ;
if ( ! E)
{
printf ( "E生成失败" ) ;
exit ( - 1 ) ;
return NULL ;
}
for ( i = 0 ; i < Graph- > Ne; i++ )
{
printf ( "请输入第%d条边: V1,V2,权重\n" , i) ;
scanf_s ( "%d %d %d" , & ( E- > v1) , & ( E- > v2) , & ( E- > weigth) ) ;
InsertEdge ( Graph, E) ;
}
}
for ( V = 0 ; V < Graph- > Nv; V++ )
{
printf ( "请输入第%d个顶点的数据\n" , V) ;
scanf_s ( "%d" , & ( Graph- > G[ V] . Data) ) ;
}
return Graph;
}
void Visit ( Ver V)
{
printf ( "正在访问顶点%d\n" , V) ;
}
void DFS ( LGraph Graph, Ver V)
{
PtrToAdjVNode W;
Visit ( V) ;
Visited[ V] = true ;
for ( W = Graph- > G[ V] . FirstEdge; W; W = W- > Next)
if ( ! Visited[ W- > AdjV] )
DFS ( Graph, W- > AdjV) ;
}
main.cpp文件
#include "Init.h"
extern bool Visited[ MaxVertexNum] ;
void main ( )
{
printf ( "无向图\n" ) ;
LGraph Graph;
Graph = BuildGraph ( ) ;
DFS ( Graph, 1 ) ;
}