关键在于两种遍历方式的理解,所以视频一定要理解清楚
图的存储结构及实现
邻接矩阵
深度优先遍历运用递归,广度优先遍历运用队列
要先理解邻接矩阵的两种遍历方式邻接矩阵深度优先遍历和广度优先遍历
- MGraph类及成员函数的实现
#pragma once
#include <iostream>
using namespace std;
const int MaxSize = 10;
int visited[MaxSize] = { 0 };//全局变量visited初始化
template <class T>
class MGraph
{
public:
MGraph(T a[], int n, int e);//构造函数
~MGraph();//析构函数
void DFTraverse(int v);//深度优先遍历图
void BFTraverse(int v);//广度优先遍历图
private:
T vertex[MaxSize];//存放图中顶点的数组
int edge[MaxSize][MaxSize];//存放途中边的数组
int vertexNum, edgeNum;//图的顶点数和边数
};
template <class T>
MGraph<T>::MGraph(T a[], int n, int e)
{
int i, j, k;
vertexNum = n;
edgeNum = e;
for (i = 0; i < vertexNum; i++)
{
vertex[i] = a[i];//存储顶点
}
for (i = 0; i < vertexNum; i++)
{
for (j = 0; j < vertexNum; j++)
{
edge[i][j] = 0;//初始化邻接矩阵
}
}
for (k = 0; k < edgeNum; k++)
{
cin >> i >> j;
edge[i][j] = 1;
edge[j][i] = 1;//设置为有边标志
}
}
template <class T>
MGraph<T>::~MGraph()
{
}
template <class T>
void MGraph<T>::DFTraverse(int v)
{
cout << this->vertex[v];
visited[v] = 1;
for (int j = 0; j < vertexNum; j++)
{
if (edge[v][j] == 1 && visited[j] == 0)
{
DFTraverse(j);
}
}
}
template <class T>
void MGraph<T>::BFTraverse(int v)
{
int w, q[MaxSize], front = -1, rear = -1;
cout << vertex[v];
visited[v] = 1;
q[++rear] = v;//入队
while (rear != front)
{
w = q[++front];//出队
for (int j = 0; j < vertexNum; j++)
{
if (edge[w][j] == 1 && visited[j] == 0)
{
cout << vertex[j];
visited[j] = 1;
q[++rear] = j;
}
}
}
}
邻接表
邻接表两种遍历方式邻接表深度优先遍历和广度优先遍历
- ALGraph类及成员函数的实现
#pragma once
#include <iostream>
using namespace std;
struct EdgeNode
{
int adjvex;//邻接点域
EdgeNode* next;
};
template <class T>
struct VertexNode
{
T vertex;
EdgeNode* firstEdge;
};
const int MaxSize = 10;
template <class T>
class ALGraph
{
public:
ALGraph(T a[], int n, int e);//构造函数
~ALGraph();//析构函数
void DFTraverse(int v);//深度优先遍历
void BFTraverse(int v);//广度优先遍历
private:
VertexNode<T> adjlist[MaxSize];//存放顶点表的数组
int vertexNum, edgeNum;//图的顶点数和边数
};
template <class T>
ALGraph<T>::ALGraph(T a[], int n, int e)
{
int i, j, k;
EdgeNode* s = nullptr;
vertexNum = n;
edgeNum = e;
for (i = 0; i < vertexNum; i++)//输入顶点信息 初始化顶点表
{
adjlist[i].vertex = a[i];
adjlist[i].firstEdge = nullptr;
}
for (k = 0; k < vertexNum; k++)
{
cin >> i >> j;
s = new EdgeNode;
s->adjvex = j;
s->next = adjlist[i].firstEdge;//头插法
adjlist[i].firstEdge = s;
}
}
template <class T>
ALGraph<T>::~ALGraph()
{
EdgeNode* p = nullptr, * q = nullptr;
for (int i = 0; i < vertexNum; i++)
{
p = q = adjlist[i].firstEdge;
while (p != nullptr)
{
p = p->next;
delete q;
q = p;
}
}
}
template <class T>
void ALGraph<T>::DFTraverse(int v)
{
}
template <class T>
void ALGraph<T>::BFTraverse(int v)
{
}