概述
1.在刚开始界面,提示用户输入要构造图的信息(边数,顶点)
2.接下会进行广度优先遍历和深度优先遍历以及打印邻接矩阵
3.源码如下所示:
#include <iostream>
#include<queue>
#include<stack>
#include<string>
const int MaxSize=100;
using namespace std;
template <typename t>
class AMGraph
{
public:
AMGraph();
~AMGraph();
int locate(t v);
void bfTraverse(int v);
void dfTraverse(int v);
void print();
void dft();
private:
t v1, v2;
int m, n;
t vertex[MaxSize];
int edge[MaxSize][MaxSize];
bool visited[MaxSize];
int vertexNum, edgeNum;
};
template<typename t>
AMGraph<t>::AMGraph()
{
//AMGraph<string> g;
cout << "请输入顶点数和边数:" << endl;
cin >> vertexNum >> edgeNum;
cout << "请输入顶点的信息:" << endl;
for (int i = 0; i < vertexNum; i++)
{
cin >> vertex[i];
}
for (int i = 0; i < vertexNum; i++)
{
for (int j = 0; j < vertexNum; j++)
{
edge[i][j] = 0;
}
}
cout << "请输入边的信息:" << endl;
for (int i = 0; i < edgeNum; i++)
{
cin >> v1 >> v2;
m = locate(v1);
n = locate(v2);
edge[m][n] = 1;
edge[n][m] = 1;
}
}
template<typename t>
AMGraph<t>::~AMGraph()
{
}
template<typename Element>
void AMGraph<Element>::dft()
{
for (int i = 0; i < vertexNum; i++)
{
visited[i] = false;
}
for (int i = 0; i < vertexNum; i++)
{
if ( !visited[i])
dfTraverse(0);
}
}
template <typename t>
void AMGraph<t>::print()
{
for (int i = 0; i < vertexNum; i++)
{
cout << endl;
for (int j = 0; j < vertexNum; j++)
{
cout << edge[i][j]<<" ";
}
}
}
template <typename t>
int AMGraph<t>::locate(t v)
{
for (int i = 0; i < vertexNum; i++)
{
if (v == vertex[i])
{
return i;
}
}
return -1;
}
template <typename t>
void AMGraph<t>::dfTraverse(int v)
{
visited[v] = true;
cout << vertex[v]<<" ";
for (int w = 0; w < vertexNum; w++)
{
if (edge[v][w] == 1 && !visited[w])
{
dfTraverse(w);
}
}
}
template<typename t>
void AMGraph<t>::bfTraverse(int v)
{
for (int i = 0; i < vertexNum; i++)
{
visited[i] = false;
}
queue<int>q;
cout << vertex[v]<<" ";
visited[v] = true;
q.push(v);
while (!q.empty())
{
v = q.front();
q.pop();
for (int j = 0; j < vertexNum; j++)
{
if (edge[v][j] == 1 && !visited[j])
{
visited[j] = true;
cout << vertex[j]<<" ";
q.push(j);
}
}
}
}
int main()
{
AMGraph<string> g;
cout << "广度优先遍历:";
g.bfTraverse(0);
cout << endl;
cout << endl;
cout << "深度优先遍历:";
g.dft();
cout << endl;
cout << endl;
cout << "领接矩阵为:" << endl;
g.print();
}
最后
以上就是自然草莓为你收集整理的图的基本操作的全部内容,希望文章能够帮你解决图的基本操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复