数据结构实验报告图实验
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图实验一,邻接矩阵的实现
1.实验目的
(1)掌握图的逻辑结构
(2)掌握图的邻接矩阵的存储结构
(3)验证图的邻接矩阵存储及其遍历操作的实现
2.实验内容
(1)建立无向图的邻接矩阵存储
(2)进行深度优先遍历
(3)进行广度优先遍历
3.设计与编码
MGraph.h
#ifndef MGraph_H
#define MGraph_H
const int MaxSize = 10;
template
class MGraph
{
public:
MGraph(DataType a[], int n, int e);
~MGraph(){
}
void DFSTraverse(int v);
void BFSTraverse(int v);
private:
DataType vertex[MaxSize];
int arc[MaxSize][MaxSize];
int vertexNum, arcNum;
};
#endif
MGraph.cpp
#include
using namespace std;
#include "MGraph.h"
extern int visited[MaxSize];
template
MGraph
int i, j, k;
vertexNum = n, arcNum = e;
for(i = 0; i < vertexNum; i++)
vertex[i] = a[i];
for(i = 0;i < vertexNum; i++)
for(j = 0; j < vertexNum; j++)
arc[i][j] = 0;
for(k = 0; k < arcNum; k++)
{
cout << "Please enter two vertexs number of edge: ";
cin >> i >> j;
arc[i][j] = 1;
arc[j][i] = 1;
}
}
template
void MGraph
{
cout << vertex[v];
visited[v] = 1;
for(int j = 0; j < vertexNum; j++)
if(arc[v][j] == 1 && visited[j] == 0)
DFSTraverse(j);
}
template
void MGraph
{
int Q[MaxSize];
int front = -1, rear = -1;
cout << vertex[v];
visited[v] = 1;
Q[++rear] = v;
while(front != rear)
{
v = Q[++front];
for(int j = 0;j < vertexNum; j++)
if(arc[v][j] == 1 && visited[j] == 0){
cout << vertex[j];
visited[j] = 1;
Q[++rear] = j;
}
}
}
MGraph_main.cpp
#include
using namespace std;
#include "MGraph.h"
extern int visited[MaxSize];
template
MGraph
int i, j, k;
vertexNum = n, arcNum = e;
for(i = 0; i < vertexNum; i++)
vertex[i] = a[i];
for(i = 0;i < vertexNum; i++)
for(j = 0; j < vertexNum; j++)
arc[i][j] = 0;
for(k = 0; k < arcNum; k++)
{
cout << "Please enter two vertexs number of edge: ";
cin >> i >> j;
arc[i][j] = 1;
arc[j][i] = 1;
}
}
template
void MGraph
{
cout << vertex[v];
visited[v] = 1;
for(int j = 0; j < vertexNum; j++)
if(arc[v][j] == 1 && visited[j] == 0)