//邻接矩阵实现深度和宽度遍历
/*数据结构实验三
完成邻接矩阵的初始化,撤销,边的搜索,插入,删除等操作 */
#include<iostream>
#include<queue>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType **a; //邻接矩阵
int n; //顶点数
int e; //当前边数
ElemType noEdge; //无边时的值
}mGraph;
int Init(mGraph *mg, int nSize, ElemType noEdgeValue) //初始化
{
int i, j;
mg->n = nSize;
mg->e = 0; //令初始化的图的边为0
mg->noEdge = noEdgeValue;
mg->a = (ElemType**)malloc(nSize * sizeof(ElemType*)); //创建一维数组指针
if (!mg->a) return 0;
for (int i = 0; i < mg->n; i++)
{
mg->a[i] = (ElemType*)malloc(nSize * sizeof(ElemType));
for (j = 0; j < mg->n; j++) mg->a[i][j] = mg->noEdge;
mg->a[i][i] = 0; //令自回路为0
}
return 0;
}
int Destory(mGraph *mg) //撤销
{
int i;
for (int i = 0; i < mg->n; i++) //利用循环释放空间
free(mg->a[i]);
free(mg->a);
return 0;
}
int Exist(mGraph *mg, int u, int v) //搜索
{
if (u<0 || v<0 || u>mg->n - 1 || v>mg->n - 1 || u == v || mg->a[u][v] == mg->noEdge)
{
cout << "这条边不存在." << endl;
return 0;
}
cout << "这条边存在." << endl;
cout << "这条边的长度为:" << mg->a[u][v] << endl;
return 0;
}
int Insert(mGraph *mg, int u, int v, ElemType w) //插入
{
if (u<0 || v<0 || u>mg->n - 1 || v>mg->n - 1 || u == v) return 0;
if (mg->a[u][v] != mg->noEdge) {
cout << "该边已存在." << endl;
return 0;
}
mg->a[u][v] = w;
mg->e++;
return 0;
}
int Remove(mGraph *mg, int u, int v) //删除
{
if (u<0 || v<0 || u>mg->n - 1 || v>mg->n - 1 || u == v)
return 0;
if (mg->a[u][v] == mg->noEdge)
return 0;
mg->a[u][v] = mg->noEdge;
mg->e--;
return 0;
}
void DFS(mGraph mg, int i, int visited[]) //深度优先遍历
{
visited[i] = 1;
cout << i << " ";
for (int j = 0; j < mg.n; j++)
{
if (mg.a[i][j] != 0 && visited[j])
DFS(mg, j, visited);
}
}
void DFSGraph(mGraph mg, int visited[])
{
int i;
for (int i = 0; i < mg.n; i++)
visited[i] = 0;
for (int i = 0; i < mg.n; i++)
if (!visited[i])
DFS(mg, i, visited);
}
void BFSGraph(mGraph *mg, int visited[]) //宽度优先遍历
{
int i, j;
queue<int> q;
for (int i = 0; i < mg->n; i++)
visited[i] = 0;
for (int i = 0; i < mg->n; i++)
{
if (!visited[i])
{
visited[i] = 1;
cout << i << " ";
q.push(i);
while (!q.empty())
{
q.pop();
for (int j = 0; j < mg->n; j++)
{
if (!visited[j] && mg->a[i][j] != 0 && !q.empty())
{
visited[j] = 1;
cout << j << " ";
q.pop();
}
}
}
}
}
}
int main()
{
mGraph mg;
int n, n1, u, v, w, a, b, visited[10010];
memset(visited, 0, sizeof(visited));
cout << "顶点数:" << endl;
cin >> n;
Init(&mg, n, 0);
cout << "插入边数:" << endl;
cin >> n1;
cout << "插入边的起点、终点和边权:" << endl;
for (int i = 0; i < n1; i++)
{
cin >> u >> v >> w;
Insert(&mg, u, v, w);
}
cout << "邻接矩阵存储下,图的深度遍历访问过的结点:";
DFSGraph(mg, visited);
cout << endl;
cout << "邻接矩阵存储下,图的宽度遍历访问过的结点:";
BFSGraph(&mg,visited);
cout << endl;
system("pause");
return 0;
}
大二(上) 数据结构 邻接矩阵实现深度和宽度遍历
最新推荐文章于 2021-11-28 22:05:52 发布