/*在这个代码里面,我主要实现的利用邻接表来存储图论,定义了一个类,里面有一个私有的node **a;这个表示的是一维的指针数组,但是在邻接矩阵实现里面也有一个int *aa,这个是动态生成二维数组,注意两者的类的构造函数和析构函数的区别,是个重点!
主要实现算法:深度宽度遍历,拓扑排序,单源最短路径dijkstra,最小生成树(prim)等等
#include<iostream>
#include<queue>
using namespace std;
const int INF = 123123123;
enum resultcode{success,failure,notpresent,overflow,duplicate};
struct node{
int adjvex;
node *next;
int w;
node(){
next = NULL;
}
node(int adj, int ww, node *ne)
{
next = ne;
w = ww;
adjvex = adj;
}
};
class graph{
private:
int n, e;
node** a;
void dfs(int v, bool *visited);
void bfs(int v, bool *visited);
void countindegree(int *indegree);
public:
graph(int size);
~graph();
resultcode insert(int u, int v, int w);
resultcode remove(int u, int v);
bool exist(int u, int v);
void bfs();
void dfs();
void toposort(int *order);
bool toposort1(int *order);
int prim(int k, int *nearest, int *lowcost);
//void floyd(int **d, int **path);floyd是采用邻接矩阵的方法实现,这个难实现
void dijsktra(int k, int *d, int *path);//书上dijskstra是采用邻接矩阵来实现的
};
graph::graph(int size)
{
n = size;
e = 0;
a = new node*[n];
for (int i = 0; i < n; i++)
{
a[i] = NULL;
}
}
graph::~graph()
{
node *p,*q;
for (int i = 0; i < n; i++)
{
p = a[i];
q = p;
while (p)
{
p = p->next;
delete q;
q = p;
}
}
delete[]a;
}
bool graph::exist(int u, int v)
{
if (u<0 || v<0 || u>n - 1 || v>n - 1 || u == v)
return false;
node *p = a[u];
while (p&&p->adjvex != v)
p = p->next;
if (!p)
return false;
else
return true;
}
resultcode graph::insert(int u, int v, int w)
{
if (u<0 ||