目录
邻接矩阵构造图
1.1 图的深度优先搜索遍历实现
1.2 图的广度优先搜索遍历实现
1.3 最短路径算法
邻接矩阵构造图
class adjancyWDigraph {
private:
//顶点数 n
int n;
//边数
int e;
//邻接矩阵
int ** a;
//当边不存在时,矩阵权值设置为noEdge;
int noEdge;
public:
//设置一个迭代器,迭代与顶点v相邻的顶点
class iterator {
private:
int * Row;
int noEdge;
int n;//共有多少个顶点
int currentVertex;
public:
iterator(int* theRow, int thenoEdge, int numberOfVertics) {
Row = theRow;
noEdge = thenoEdge;
n = numberOfVertics;
currentVertex = 1;
}
int next() {
for (int j = currentVertex; j <= n; j++) {
if (Row[j] != noEdge) {
currentVertex = j + 1;
return j;
}
}
currentVertex = n + 1;
return 0;
}
};
void bfs(int v, int reach[]);
void dfs(int v, int reach[]);
//生成一个指向顶点v迭代器的指针
iterator * makeIterator(int theVertex) {
return new iterator(a[theVertex], noEdge, n);
}
};
1.1 图的深度优先搜索遍历实现
void adjancyWDigraph::bfs(int v, int reach[]) {
//创建一个队列
queue q;
//将头节点加入队列
q.push(v);
reach[v] = true;
while (!q.empty()) {
//取出q中的第一个结点,然后从队列中删除
int w = q.front();
q.pop();
//初始化节点的迭代器,找到与他相连的节点
iterator *iw = makeIterator(w);
int u;
//当节点的相邻节点存在时
while ((u = iw->next()) != 0) {
if (reach[u] == 0) {
q.push(u);
reach[u] = true;
}
}
delete iw;
}
}
1.2 图的广度优先搜索遍历实现
void adjancyWDigraph::dfs(int v, int reach[]) {
reach[v] = true;
iterator *iw = makeIterator(v);
int u;
while ((u = iw->next()) != 0&&reach[u]!=true) {
dfs(u, reach);
}
delete iw;
}
1.3 最短路径算法
void adjancyWDigraph:: BFS_MIN_DISTANCE(int v, int reach[], int d[], int path[]) {
//为了方便考虑,假设所有权值为1
//d[]表示顶点v到i的最短距离,path表示是从哪个顶点过来的,初始化一下这两个数组
for (int i = 1; i < n; i++) {
d[i] = 100000;
path[i] = -1;
reach[i] = false;
}
d[v] = 0;
reach[v] = true;
queue q;
q.push(v);
while (!q.empty()) {
int w = q.front();
q.pop();
iterator *iw = makeIterator(w);
int u;
//当节点的相邻节点存在时,遍历
while ((u = iw->next()) != 0) {
if (reach[u] == false) {
d[u] = d[w] + 1;
path[u] = w;
q.push(u);
reach[u] = true;
}
}
delete iw;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)