Topological Sorting

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */    
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // an arraylist to save the result
        ArrayList<DirectedGraphNode> ret = new ArrayList<>();
        
        // calculate indegree for the nodes in the graph
        // using a hashmap to save the <node, indegree> pair
        HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
        for (DirectedGraphNode node : graph) {
            // list all neighbors of the node 
            for (DirectedGraphNode neighbor : node.neighbors) {
                if (map.containsKey(neighbor)) {
                    map.put(neighbor, map.get(neighbor)+1);
                }
                else {
                    map.put(neighbor, 1);
                }
            }
        }
        
        // find the root(s) in graph, note that root does not exist in the map
        // put all root(s) into the queue
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        for (DirectedGraphNode node : graph) {
            if (!map.containsKey(node)) {
                queue.offer(node);
                ret.add(node);
            }
        }
        
        // do the BFS in the graph
        while (!queue.isEmpty()) {
            // we don't need a for loop to iterate all nodes in the queue b/c we just need to return one 
            // topological order for the given graph
            DirectedGraphNode node = queue.poll();    
            for (DirectedGraphNode neighbor : node.neighbors) {
                // decrease all indegree of node's neighbors by 1 b/c we just add node to our result
                map.put(neighbor, map.get(neighbor)-1);
                // if a node's indegree is 0, we need to put it into the queue
                if (map.get(neighbor) == 0) {
                    queue.offer(neighbor);
                    ret.add(neighbor);
                }
            }
        }
        
        return ret;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是C语言代码实现: ```c #include <stdio.h> #include <stdlib.h> #define MAX_VERTEX_NUM 20 // 图的最大顶点数 // 边表结点 typedef struct ArcNode { int adjvex; // 该边所指向的顶点的位置 struct ArcNode *next; // 指向下一条边的指针 } ArcNode; // 顶点表结点 typedef struct VertexNode { char data; // 顶点信息 ArcNode *firstarc; // 指向第一条依附该顶点的边的指针 } VertexNode; // 图的邻接表 typedef struct { VertexNode vertexes[MAX_VERTEX_NUM]; // 顶点表 int vexnum, arcnum; // 图的当前顶点数和边数 int kind; // 图的种类(有向图或无向图) } ALGraph; // 创建图的邻接表 void CreateGraph(ALGraph *G) { int i, j, k; char ch; ArcNode *p; printf("要建立的是有向图(1)还是无向图(0),请选择(输入1或0):"); scanf("%d", &G->kind); printf("请输入图的顶点数:"); scanf("%d", &G->vexnum); printf("请输入图的边数:"); scanf("%d", &G->arcnum); printf("请输入图的各顶点信息:\n"); for (i = 0; i < G->vexnum; i++) { getchar(); // 吸收上一行的回车符 printf("第%d个顶点信息:", i+1); scanf("%c", &ch); G->vertexes[i].data = ch; G->vertexes[i].firstarc = NULL; } printf("请输入边的信息,格式为:序号1,序号2(序号依次为0、1、2……):\n"); for (k = 0; k < G->arcnum; k++) { printf("请输入第%d条边:", k); scanf("%d,%d", &i, &j); // 新建一个边表结点 p = (ArcNode*) malloc(sizeof(ArcNode)); p->adjvex = j; // 将该边表结点插入到i所在顶点的边表头部 p->next = G->vertexes[i].firstarc; G->vertexes[i].firstarc = p; // 如果是无向图,还需要将该边表结点插入到j所在顶点的边表头部 if (G->kind == 0) { p = (ArcNode*) malloc(sizeof(ArcNode)); p->adjvex = i; p->next = G->vertexes[j].firstarc; G->vertexes[j].firstarc = p; } } } // 输出图的邻接表 void PrintGraph(ALGraph *G) { int i; ArcNode *p; printf("图的邻接表表示如下:\n"); for (i = 0; i < G->vexnum; i++) { printf("%d\t[%c](", i, G->vertexes[i].data); p = G->vertexes[i].firstarc; while (p != NULL) { printf("%d", p->adjvex); p = p->next; if (p != NULL) { printf(" "); } } printf(")\n"); } } int main() { ALGraph G; CreateGraph(&G); PrintGraph(&G); return 0; } ``` 运行程序后,按照提示输入相应的信息即可创建并输出图的邻接表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值