DFS

29 阅读2分钟

基于c语言实现深度优先遍历:

输入 8,10 1 2 3 4 5 6 7 8 1,2 1,5 2,6 3,6 3,7 3,4 4,7 4,8 6,7 7,8 2

输出

请输入顶点数和边数:请输入顶点本身的数据:

请输入边的数据:

0 1 0 0 1 0 0 0

1 0 0 0 0 1 0 0

0 0 0 1 0 1 1 0

0 0 1 0 0 0 1 1

1 0 0 0 0 0 0 0

0 1 1 0 0 0 1 0

0 0 1 1 0 1 0 1

0 0 0 1 0 0 1 0

输入DFS遍历的起始结点:2 1 5 6 3 4 7 8

6a7eda05d5b5636b3e76d4aa8988.png

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
//#include <iostream>
#define MAX_VERTICES 100 //假设图有100个顶点
#define MAX_WEIGHT 32767 //加权图(网)不邻接时为10000,但输出为“∞”
#define Maxsize 100

typedef struct
{
	int Vertices[MAX_VERTICES]; //顶点信息的数组
	int AdjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; //边信息的数组。
	int numV; //当前的顶点数
	int numA; //当前的边数
}AdMatrix;
typedef struct
{
	int  *base;
	int front;
	int rear;
}CyQueue;


//图的生成函数
void CreateGraph(AdMatrix *G)
{
    int n, e, vi, vj;
	printf("请输入顶点数和边数:");
	scanf("%d,%d", &n, &e);
	G->numV = n;
	G->numA = e;
	//Vertices数组的创建
	printf("请输入顶点本身的数据:\n");
	for (int i = 0; i < G->numV; i++)
	{

		scanf("%d", &G->Vertices[i]);
	}
	//AdjacencyMatrix数组的建立
	printf("请输入边的数据:\n");
	for (int i = 0; i < G->numA; i++)
	{
		scanf("%d,%d", &vi, &vj);
		G->AdjacencyMatrix[vi - 1][vj - 1] = 1;
		G->AdjacencyMatrix[vj - 1][vi - 1] = 1;
	}
}
//输出邻接矩阵的信息
void ShowGraph(AdMatrix *G)
{
	int i, j;
	for (i = 0; i < G->numV; i++)
	{
		//printf("\n%d ", i + 1);
		for (j = 0; j < G->numV; j++)
		{
			/*if (G->AdjacencyMatrix[i][j] == MAX_WEIGHT)
			{
				printf("%s ", "∞");
			}
			else
			{
				printf("%d ", G->AdjacencyMatrix[i][j]);
			}*/
			printf("%d ", G->AdjacencyMatrix[i][j]);
		}
		printf("\n");
	}
}


/*循环队列基本操作*/
void create(CyQueue *q)
{
	q->base=(int  *)malloc(Maxsize*sizeof(int));
	if(!q->base)
	{
		printf("Space allocation failed!\n");
		return;
	}
	q->front=q->rear=0;
	return;
}

void EnQueue(CyQueue *q,int value)
{
	if((q->rear+1)%Maxsize==q->front)
	{
		printf("Cyclic Queue is Full!\n");
		return;
	}
	q->base[q->rear]=value;
	q->rear=(q->rear+1)%Maxsize;
	return;
}

void DeQueue(CyQueue *q,int *value)
{
	if(q->front==q->rear)
	{
		printf("Cyclic Queue is Empty!\n");
		return;
	}
	*value=q->base[q->front];
	q->front=(q->front+1)%Maxsize;
	return;
}

int QueueEmpty(CyQueue *q)
{
    if (q->front==q->rear)//队列为空返回1,不为空返回0
	{
        return 1;
    }
    return 0;
}

/*广度优先遍历BFS*/
int visited[MAX_VERTICES];//定义"标志"数组为全局变量

void DFS(AdMatrix *G,int i)
{
	int j;

	//1.处理起始点
	printf("%d ",G->Vertices[i]);//1.输出起始结点
	visited[i]=1;//2.将已访问的结点标志成1

	 //2.由起始点开始,对后续结点进行操作
	for(j=0;j<G->numV;j++)//依次搜索vi的邻接点
	{
		if(G->AdjacencyMatrix[i][j]==1&&visited[j]==0)//当满足有边且未被访问过时,递归调用去查找该邻接点
		{
			DFS(G,j);//注意此处的G已经是指针类型,不需要再&G
		}
	}

}

int main()
{
	AdMatrix G;
	CreateGraph(&G);
	ShowGraph(&G);
	printf("输入DFS遍历的起始结点:");
	int n;
	scanf("%d",&n);
	DFS(&G,n-1);
	return 0;
}