文章目录
图的实现
1. Graph类
Graph类定义图的基本信息(边与顶点)的相关内容,以及广度优先算法与深度优先算法等。
#pragma once
#include <assert.h>
#include <limits.h> // INT_MAX
#include "../dsa_queue_20200717/queue.h"
#include "../dsa_stack_20200716/stack.h"
namespace dtl
{
// 顶点状态
enum class VertexStatus {
// 未发现
undiscovered,
// 已发现
discovered,
// 已访问
visited,
};
// 边状态
enum class EdgeStatus {
// 未处置
undetermined,
// 树边
tree,
// 跨边
cross,
// 前向边
forward,
// 后向边
backward,
};
// class of GRAPH
template <typename Tv, typename Te>
class Graph
{
private:
// 所有顶点、边的辅助信息复位
void reset() {
for (int i = 0; i < n; i++) {
status(i) = VertexStatus::undiscovered;
dTime(i) = fTime(i) = -1;
parent(i) = -1;
priority(i) = INT_MAX;
for (int j = 0; j < n; j++) {
if (exists(i, j))
type(i, j) = EdgeStatus::undetermined;
}
}
}
// breadth first search
void BFS(int v, int& clock) {
#if DSA_MODE
printf("BFS in with v=%d, clock=%d\n", v, clock);
#endif
Queue<int> queue;
status(v) = VertexStatus::discovered;
queue.enqueue(v);
#if DSA_MODE
printf("vetex v=%d", v); print(vertex(v)); printf(" status changed to VertexStatus::discovered\n");
printf("current Q: "); print(queue);
#endif
while (!queue.empty()) {
int v = queue.dequeue();
dTime(v) = ++clock;
#if DSA_MODE
printf("visiting vertex v=%d", v); print(vertex(v)); printf("["); print(status(v)); printf("] dTime=%d\n", clock);
#endif
for (int u = firstNbr(v); -1 < u; u = nextNbr(v, u)) {
#if DSA_MODE
printf("visiting vertex u=%d", u); print(vertex(u)); printf("["); print(status(u)); printf("]\n");
#endif
if (status(u) == VertexStatus::undiscovered) {
status(u) = VertexStatus::discovered;
queue.enqueue(u);
type(v, u) = EdgeStatus::tree;
parent(u) = v;
} else {
type(v, u) = EdgeStatus::cross;
}
#if DSA_MODE
printf("edge(%d, %d) ", v, u); print(vertex(v)); printf(" ->"); print(vertex(u)); printf(" now is "); print(type(v, u)); printf("\n");
#endif
}
status(v) = VertexStatus::visited;
#if DSA_MODE
printf("vetex v=%d", v); print(vertex(v)); printf(" status changed to VertexStatus::visited\n");
printf("current Q: "); print(queue);
#endif
}