考研二战日记-第九天—数据结构:图(二)

昨天是对图的知识点总结,这一部分内容大多是以大题形式出现,但是也不排除代码题出现的可能性

图的完整代码实现

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;
        }
    }
}

另外求最小生成树,最短路径等综合题只要自己做过例题找准解题步骤就能拿到自己想要的分数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值