#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
typedef struct node
{
int adjvex;//邻接点域
struct node* next;
}EdgeNode;
typedef struct vnode
{
int vertax;//顶点域
EdgeNode* firstedge;
}VertaxNode;
void CreatAdjlist(VertaxNode g[], int e, int n)//n:顶点数,e:边数,g[]存储n个顶点表的节点
{
EdgeNode* p;
int i, j, k;
printf("input data of vertax\n");
for ( i = 0; i < n; i++)
{
g[i].vertax = i;
g[i].firstedge = NULL;
}
for ( k = 1; k <=e; k++)
{
printf("input edge of(i,j)\n");
scanf_s("%d%d", &i, &j);
p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->next = g[i].firstedge;
g[i].firstedge = p;
p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->adjvex = i;
p->next = g[j].firstedge;
g[j].firstedge = p;
}
}
int visited[MAXSIZE];
void DFS(VertaxNode g[], int i)
{
EdgeNode* p;
printf("%4d", g[i].vertax);
visited[i] = 1;
p = g[i].firstedge;
while (p!=NULL)
{
if (!visited[p->adjvex])
DFS(g, p->adjvex);
p = p->next;
}
}
void DFSTeaverse(VertaxNode g[], int n)
{
int i;
for ( i = 0; i < n; i++)
{
visited[i] = 0;
}
for ( i = 0; i < n; i++)
{
if (!visited[i])
DFS(g, i);
}
}
void main(void)
{
int e, n;
VertaxNode g[MAXSIZE];
printf("输入图的结点数\n");
scanf_s("%d", &n);
printf("输入图中边数\n");
scanf_s("%d", &e);
CreatAdjlist(g, e, n);
printf("dfs:\n");
DFSTeaverse(g, n);
printf("\n");
}
DFS搜索树
最新推荐文章于 2023-01-02 09:43:00 发布