昨天是对图的知识点总结,这一部分内容大多是以大题形式出现,但是也不排除代码题出现的可能性
图的完整代码实现
class Graph<T>(private val vertices: ArrayList<Vertex<T>> = ArrayList(),
private val adjacencyList: ArrayList<EdgeList<T>> = ArrayList()) {
fun createVertex(value: T): Vertex<T> {
val matchingVertices = vertices.filter { it.data == value }
if (matchingVertices.isNotEmpty()) {
return matchingVertices.last()
}
val vertex = Vertex(value, adjacencyList.size)
vertices.add(vertex)
adjacencyList.add(EdgeList(vertex))
return vertex
}
fun addDirectedEdge(fromVertex: Vertex<T>, toVertex: Vertex<T>, weightValue: Double) {
val edge = Edge(from = fromVertex,
to = toVertex,
weight = weightValue)
fromVertex.addEdge(edge)
val fromIndex = vertices.indexOf(fromVertex)
adjacencyList[fromIndex].edges.add(edge)
}
fun addUnDirectedEdge(fromVertex: Vertex<T>, toVertex: Vertex<T>, weightValue: Double = 0.0) {
addDirectedEdge(fromVertex, toVertex, weightValue)
addDirectedEdge(toVertex, fromVertex, weightValue)
}
fun printAdjacencyList() {
(0 until vertices.size)
.filterNot { adjacencyList[it].edges.isEmpty() }
.forEach { println("""${vertices[it].data} ->[${adjacencyList[it].edges.joinToString()}] """) }
}
}
DFS(深度优先遍历)
int visit[maxSize];
void DFS(AGraph *G, int v) {
ArcNode *p;
visit[v] = 1;
cout << v << endl;
p = G->adjlist[v].firstarc; // 让p指向顶点v的第一条边
while (p != nullptr) {
if (visit[p->adjvex] == 0) {
DFS(G, p->adjvex);
p = p->nextarc;
}
}
}
BFS(广度优先遍历)
void BFS(AGraph *G, int v) {
ArcNode *p;
int que[maxSize], front = 0, rear = 0; // 定义一个队列
int j;
cout << v << endl;
visit[v] = 1;
rear = (rear+1)%maxSize; // 入队
que[rear] = v;
while (front != rear) {
front = (front+1)%maxSize; // 顶点出队
j = que[front];
p = G->adjlist[j].firstarc; // p指向出队顶点j的第一条边
while (p != nullptr) { // 将p的所有邻接点未被访问的入队
if (visit[p->adjvex] == 0) {
cout << p->adjvex << endl;
rear = (rear+1)%maxSize;
que[rear] = p->adjvex;
}
p = p->nextarc;
}
}
}
另外求最小生成树,最短路径等综合题只要自己做过例题找准解题步骤就能拿到自己想要的分数。