/********************************************************************
created: 2014/10/04
created: 4:10:2014 14:48
filename: D:\我的文档\visual c++\数据结构\GraphTest\MGraph\MGraph.cpp
file path: D:\我的文档\visual c++\数据结构\GraphTest\MGraph
file base: MGraph
file ext: cpp
author:
purpose:
*********************************************************************/
#include "StdAfx.h"
#include <IOSTREAM>
using namespace std;
const int MaxSize = 10;
template <class DataType>
class MGraph
{
public:
MGraph(DataType a[], int n, int e);
~MGraph();
void DFSTraverse(int v);
void BFSTraverse(int v);
private:
DataType vertex[MaxSize], visited[MaxSize];
int arc[MaxSize][MaxSize];
int vertexNum, arcNum, Top, front, rear;
int data[MaxSize], Q[MaxSize];
};
template <class DataType>
MGraph<DataType>::MGraph(DataType a[], int n, int e)
{
Top = -1;
vertexNum = n; arcNum = e;
//给顶点编号,初始化visited数组
for (int i = 0; i < vertexNum ; i++)
{
vertex[i] = a [i];
visited[i] = 0;
}
//初始化邻接矩阵
for (i = 0; i < vertexNum ; i++)
for (int j = 0; j < vertexNum ; j++)
arc[i][j] = 0;
//给每条边赋值
for (int k = 0; k < arcNum; k++)
{
int j;
cout <<"please input the number of each vertex of the arc"<<std::endl;
cin >>i>>j;
arc[i][j] = 1;
arc[j][i] = 1;
}
}
template <class DataType>
void MGraph<DataType>::DFSTraverse(int v)
{
data[++Top] = v; visited[v] = 1;
for (int j = 0; j < vertexNum ; j++)
if (visited[j] ==0 && arc[v][j] == 1)
DFSTraverse(j);
cout <<vertex[data[Top--]]<< "->" ;
}
template <class DataType>
void MGraph<DataType>::BFSTraverse(int v)
{
front = rear = -1;
cout <<vertex[v]<<"->";
visited[v] = 1;
rear = (rear++)%MaxSize;
Q[rear] = v; //入队
while (front != rear)
{
front = (front++)%MaxSize;
v = Q[front]; //出队
//这个循环将读取到V顶点的未曾被访问的邻接点
for (int i = 0; i < vertexNum; i++) //遍历可能的邻接点
{
if (arc[v][i] == 1 && visited[i] == 0)//只对未曾被访问的邻接点做出处理:读取、入队、打标志
{
rear = (rear++)%MaxSize;
Q[rear] = i; visited[i] = 1; //入队
cout <<vertex[Q[rear]]<<"->";
}
}
}
}
int main(int argc, char* argv[])
{
double a[6] = {0, 1.1, 2.1, 3.1, 4.1, 5.1};
MGraph<double>* test = new MGraph<double>(a, 6, 6);
cout <<"请输入根节点编号(自定)"<<endl;
int root;
cin >> root;
//test->DFSTraverse(root);
test->BFSTraverse(root);
return 0;
}
图的邻接矩阵存储及其遍历(使用模板)
原文作者:数据结构之图
原文地址: https://blog.csdn.net/u011450367/article/details/39829681
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/u011450367/article/details/39829681
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。