图的邻接矩阵表示法非常简单,一个定点数组,一个二维数组搞定,类似与这样
下面简单实现一个邻接矩阵表示的方法的图,以及遍历的两种方式。
Graph.h
#pragma once
#define MAX_SIZE 30
template<class T,class E>
class Graph
{
public:
Graph(size_t size);
virtual ~Graph();
bool isEmpty()const {
return verticleSize == 0;
}
int numberofVerticles(){
return verticleSize ;
}
protected:
int maxVerticles=MAX_SIZE;
int verticleSize;
virtual T getValue(int i) = 0; //获取值
virtual E getWeight(int v1, int v2) = 0; //根据两个定点获取边的权值
virtual int getFirstNeighbor(int v) = 0; //取顶点v的第一个邻接顶点
virtual int getNextNeighbor(int v, int w) = 0; //取邻接顶点w的下一个邻接顶点
virtual int getVertexPos(T vertex) = 0; //由定点获取下标
virtual T* getVerticles() = 0; //获取定点数量
};
template<class T, class E>
Graph<T, E>::Graph(size_t size):verticleSize(size)
{
}
template<class T, class E>
inline Graph<T, E>::~Graph()
{
}
父类只是定义了一些基本方法,不再赘述。
遍历方式
我们按照深度遍历的顺序,假设从v1开始,那么数序是v1->v0->v4->v2->v3
同样从v1开始,顺序是v1->v0->v2->v4->v3
GraphMatrix.h
#pragma once
#include "Graph.h"
#include <iostream>
#include <stack>
#include <queue>
#define INF 0xffffff
using namespace std;
template<class T, class E>
class GraphMatrix :public Graph<T, E>
{
public:
GraphMatrix(size_t size);
~GraphMatrix();
static const int MAX_WEIGHT = INF;
T getValue(int