最全图算法(dfs,bfs,最短路,最小生成树,拓扑排序)

//邻接矩阵实现
#include
#include
#define v_max 10
#define e_max 100
using namespace std;
class graph
{
private:
	int v_num;										//节点数
	int e_num;										//边数
	int edge[v_max][v_max];
	int visited[v_max];
public:
	graph(int v, int e);
	void creategraph(int v, int e);
	void print();
	void dfs(int i);
	void dfs_();
	void bfs(int v);
	void bfs_();
};
graph::graph(int v, int e) :v_num(v), e_num(e)
{
	creategraph(v, e);
}
void graph::creategraph(int v, int e)
{
	for (int i = 0; i < v_max; i++)
		for (int j = 0; j < v_max; j++)
		{
			if (i != j)
				edge[i][j] = INT_MAX;
			else
				edge[i][j] = 0;
		}
	for (int i = 0; i < e; i++)
	{
		int s, d, w;
		cin >> s >> d >> w;
		edge[s][d] = w;
	}
}
void graph::print()
{
	for (int i = 0; i < v_max; i++)
	{
		cout << i << "节点相邻接点: ";
		for (int j = 0; j < v_max; j++)
		{
			if (edge[i][j] != INT_MAX && edge[i][j] != 0)
				cout << j << ' ';
		}
		cout << endl;
	}
}
void graph::dfs_()
{
	for (int i = 0; i < v_max; i++)
	{
		visited[i] = 0;
	}
	cout << "访问顺序:";
	for (int i = 0; i < v_num; i++)
	{
		if (!visited[i])
		{
			cout << i << "->";
			visited[i] = 1;
			dfs(i);
		}

	}
}
void graph::dfs(int i)
{
	for (int j = 0; j < v_max; j++)
	{
		if (!visited[j] && edge[i][j] != 0 && edge[i][j] != INT_MAX)
		{
			cout << j << "->";
			visited[j] = 1;
			dfs(j);
		}
	}
}
void graph::bfs(int v)
{
	queueq;
	q.push(v);
	
	while (!q.empty())
	{
		int w = q.front();
		cout << w << "->";
		q.pop();
		for (int i = 0; i < v_num; i++)
		{
			if (!visited[i] && edge[w][i] != 0 && edge[w][i] != INT_MAX)
			{
				visited[i] = 1;
				q.push(i);
			}
		}
	}
}
void graph::bfs_()
{
	for (int i = 0; i < v_max; i++)
	{
		visited[i] = 0;
	}
	for (int i = 0; i < v_num; i++)
	{
		if (!visited[i])
		{
			visited[i] = 1;
			bfs(i);
		}
	}
}

未完待续

你可能感兴趣的:(最全图算法(dfs,bfs,最短路,最小生成树,拓扑排序))