拓扑排序

TOPOLOGICAL-SORT(G)
1 call DFS(G) to compute finishing times v.f for each vertex v
2 as each vertex is finished, insert it onto the front of a linked list
3 return the linked list of verteces

java代码如下:

    /**
     * 拓扑排序
     * @param graphContent
     * @return
     * @throws Exception
     */
    public static LinkedList<Vertex> topo_sort(String graphContent) throws Exception{
        if (hasLoop(graphContent)){
            throw new Exception("this graph has loop");
        }

        LinkedList<Vertex> list = new LinkedList<Vertex>();

        List<Vertex> vertexs = Route.getVertexs(graphContent);

        for (Vertex vertex : vertexs){
            vertex.setColor(Color.WHITE);
            vertex.setParent(null);
        }
        for (Vertex vertex : vertexs){
            if (vertex.getColor().equals(Color.WHITE)){
                DFS_VISIT(graphContent, vertex, list);
            }
        }
        return list;
    }

    /**
     * 检查是否有环,没有含有入度为0的节点则必然有环
     * @param graphContent
     * @return
     */
    @SuppressWarnings("rawtypes")
    private static boolean hasLoop(String graphContent) {
        // TODO Auto-generated method stub
        List<Vertex> vertexs = Route.getVertexs(graphContent);
        LinkedList[] lists = Route.getLinkedList(graphContent);

        int count = 0;
        for (Vertex vertex : vertexs){
            for (LinkedList l : lists){
                for (int i = 1; i < l.size(); i++){
                    if (vertex.equals(l.get(i))){
                        count++;
                    }
                }
            }
            if (count == 0){
                return false;
            }else {
                count = 0;
            }
        }       
        return false;
    }

    private static int time = 0;

    @SuppressWarnings("rawtypes")
    public static void DFS_VISIT(String graphContent, Vertex vertex, LinkedList<Vertex> list){
        LinkedList[] lists = Route.getLinkedList(graphContent);

        time = time + 1;
        vertex.setS(time);
        vertex.setColor(Color.GRAY);
        for (Object v : lists[vertex.getID()]){
            Vertex V = (Vertex)v;
            if (V.getColor().equals(Color.WHITE)){
                V.setParent(vertex);
                DFS_VISIT(graphContent, V, list);
            }
        }
        vertex.setColor(Color.BLACK);
        time = time + 1;
        vertex.setF(time);
        list.addFirst(vertex);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值