数据结构与算法编程题58-无向邻接表的DFS算法

无向邻接表的DFS算法

#include 
using namespace std;

#define VexNum 10
typedef	int VertexType;


typedef struct ArcNode
{
	int adjvex;
	int weight;
	struct ArcNode* nextarc;
}ArcNode;

typedef struct VNode
{
	VertexType data;
	struct ArcNode* firstarc;
}VNode,VNodeList[VexNum];

typedef struct Graph
{
	VNodeList Vex;
	int arcnum;
	int vexnum;
}Graph;

int LocateVex(Graph G, VertexType v)
{
	for (int i = 0; i < G.vexnum; i++)
	{
		if (G.Vex[i].data == v)
			return i;
	}
	return -1;
}

//创建无向图
void Create_UGraph(Graph &G)
{
	int i = 0,j = 0;
	int k = 0;
	cout << "请输入顶点数和边数:  ";  
	cin >> G.vexnum >> G.arcnum;
	for (i = 0; i < G.vexnum; i++)
	{
		G.Vex[i].data = 0;
		G.Vex[i].firstarc = NULL;
	}
	for (i = 0; i < G.vexnum; i++)
	{
		cout << "请输入第" << i << "个顶点: ";
		cin >> G.Vex[i].data;
	}

	for (k = 0; k < G.arcnum; k++)
	{
		cout << "请输入第" << k+1<< "条边: ";
		VertexType v1, v2;
		cin >> v1 >> v2;
		i = LocateVex(G, v1);
		j = LocateVex(G, v2);
		ArcNode* p1 = NULL;
		p1 = (ArcNode*)malloc(sizeof(ArcNode));
		if (p1 == NULL)
		{
			cout << "内存地址分配失败" << endl;
			exit(0);
		}
		p1->adjvex = j;
		p1->nextarc = G.Vex[i].firstarc;
		G.Vex[i].firstarc = p1;

		ArcNode* p2 = NULL;
		p2 = (ArcNode*)malloc(sizeof(ArcNode));
		if (p2 == NULL)
		{
			cout << "内存地址分配失败" << endl;
			exit(0);
		}
		p2->adjvex = i;
		p2->nextarc = G.Vex[j].firstarc;
		G.Vex[j].firstarc = p2;
	}
}

void Print_Graph(Graph G)
{
	ArcNode* p = NULL;
	for(int i = 0;i<G.vexnum;i++)
	{ 
		p = G.Vex[i].firstarc;
		cout << i << "  ";
		while (p != NULL)
		{
			cout<< "---->"<<p->adjvex;
			p = p->nextarc;
		}
		cout << endl;
	}
}

int visited[VexNum] = {0};
//-------------------------------DFS算法-------------------------------//
void DFS(Graph G, VertexType v)
{
	ArcNode* p = NULL;
	int locate = LocateVex(G, v);
	p = G.Vex[locate].firstarc;
	cout << v << endl;
	visited[locate] = 1;
	int w = 0;
	while (p != NULL)
	{
		w = G.Vex[p->adjvex].data;
		if (visited[p->adjvex] == 0)
			DFS(G, w);
		p = p->nextarc;
	}
}
//-------------------------------DFS算法-------------------------------//
//顶点数和边数
//5   8
//顶点具体数
//1 2 3 4 5
//边具体情况
//1 2
//1 3
//1 4
//2 3
//3 4
//2 5
//3 5
//4 5
int main(void)
{
	Graph G;
	Create_UGraph(G);
	Print_Graph(G);
	DFS(G, 1);
	return 0;
}

数据结构与算法编程题58-无向邻接表的DFS算法_第1张图片

你可能感兴趣的:(算法与数据结构,数据结构)