理论原理:
代码实现:
#include <iostream>
#include <queue>
using namespace std;
#define N 5
struct Graph
{
//顶点信息
char vertex[N];
//边信息
int edg[N][N];
};
static bool visited[N]={false};
void visit(Graph graph,int index)
{
visited[index]=true;
cout<<graph.vertex[index]<<" ";
}
void DFS_Connect(Graph graph,int index)
{
visit(graph,index);
for(int i=0;i<N;i++)
{
if(graph.edg[index][i]==1 && !visited[i])
{
DFS_Connect(graph,i);
}
}
}
void DFS(Graph graph,int index)
{
DFS_Connect(graph,index);
for(int i=0;i<N;i++)
{
if(!visited[i])
{
DFS_Connect(graph,i);
}
}
}
int main()
{
//初始化图
Graph graph = {
{'1','2','3','4','5'},
{
{0,1,1,1,0},
{1,0,0,1,1},
{1,0,0,0,1},
{1,1,0,0,1},
{0,1,1,1,0},
}
};
DFS(graph,4);
return 0;
}
运行结果: