数据结构__vetor邻接表实现图的DFS(深度优先遍历)

用的是上一会STL创立的邻接表。

代码给出:

#include<iostream>
#include<vector>
#define maxn 1000
bool vis[maxn] = { false };
using namespace std;

struct node
{
	int adjvex;
	char data;
	int weight;
};

vector<node> adj[maxn];
int n;

void createNode(char a,int i,int w=0)
{
	node temp;
	temp.adjvex = a-'a';
	temp.data = a;
	temp.weight = w;
	adj[i].push_back(temp);
}

void create()
{
	int m;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		char tempA;
		cin >> tempA;
		createNode(tempA, i);
	}
	char a, b;
	int cost,aa,bb;
	for (int i = 0; i < m; i++)
	{
		cin >> a >> b >> cost;
		for (int j = 0; j < n; j++)
		{
			if (a == adj[j][0].data)
				aa = adj[j][0].adjvex;
		}
		createNode(b, aa, cost);
	}
}

void print()
{
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < adj[i].size(); j++)
		{
			cout << adj[i][j].data <<adj[i][j].weight << ' ';
		}
		cout << endl;
	}
}

void DFS(int u, int depth)
{
	vis[u] = true;
	for (int i = 0; i < adj[u].size(); i++)
	{
		int v = adj[u][i].adjvex ;
		if (vis[v] == false)
		{
			cout << adj[u][i].data;
			DFS(v, depth + 1);
		}
	}
}

void DFSTrave()
{
	for (int u = 0; u < n; u++)
	{
		if (vis[u] == false)
		{
			cout << adj[u][0].data;
			DFS(u, 1);
		}
	}
}

int main(void)
{
	create();
	print();
	DFSTrave();
	system("pause");
	return 0;
}

这是第一组I/O。

再给出第二组:

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/86548630