图论算法——有向图的可达性与寻路

引言

本篇博文探讨了有向图的可达性(即给定起点与某个点是否连通)以及寻路问题。
有关图的概念可参考博文数据结构之图的概述

示例图如下:
在这里插入图片描述

有向图的可达性

利用了有向图的深度优先算法,它解决了单点连通性的问题,可以判定其他顶点和给定的起点是否连通。

package com.algorithms.graph;


/**
 * @author yjw
 * @date 2019/5/20/020
 */
public class DirectedDFS {
    private boolean[] marked;

    public DirectedDFS(DiGraph g, int s) {
        marked = new boolean[g.vertexNum()];
        dfs(g, s);
    }

    /**
     * 在有向图中找到从sources中的所有顶点可达的所有顶点
     *
     * @param g
     * @param sources
     */
    public DirectedDFS(DiGraph g, Iterable<Integer> sources) {
        marked = new boolean[g.vertexNum()];
        for (int s : sources) {
            if (!marked[s]) {
                dfs(g, s);
            }
        }
    }

    private void dfs(DiGraph g, int v) {
        marked[v] = true;
        for (int w : g.adj(v)) {
            if (!marked[w]) {
                dfs(g,w);
            }
        }
    }

    /**
     * 返回顶点v是从已知顶点(s或sources)中可达的吗
     * @param v
     * @return
     */
    public boolean marked(int v) {
        return marked[v];
    }

    public static void main(String[] args) {
        DiGraph dg = new DiGraph(6);
        dg.addEdge(0,2,2,0,2,1,2,3,3,2,3,4,3,5);
        DirectedDFS dfs = new DirectedDFS(dg,3);
        for (int v = 0; v < dg.vertexNum(); v++) {
            if (dfs.marked[v]) {
                System.out.print(v + " ");
            }
        }
        System.out.println();

    }
}

我们验证了示例有向图,从3出发到所有顶点都是可达的。

有向图的寻路

package com.algorithms.graph;

import com.algorithms.stack.Stack;

/**
 * @author yjw
 * @date 2019/5/20/020
 */
public class DepthFirstDirectedPaths {
    private boolean[] marked;  
    private int[] edgeTo;     
    private final int s;      

  
    public DepthFirstDirectedPaths(DiGraph g, int s) {
        marked = new boolean[g.vertexNum()];
        edgeTo = new int[g.vertexNum()];
        this.s = s;
        dfs(g, s);
    }

    private void dfs(DiGraph g, int v) {
        marked[v] = true;
        for (int w : g.adj(v)) {
            if (!marked[w]) {
                edgeTo[w] = v;
                dfs(g, w);
            }
        }
    }

    public boolean hasPathTo(int v) {
        return marked[v];
    }


    public Iterable<Integer> pathTo(int v) {
        if (!hasPathTo(v)) return null;
        Stack<Integer> path = new Stack<>();
        for (int x = v; x != s; x = edgeTo[x]) {
            path.push(x);
        }
        path.push(s);
        return path;
    }

    public static void main(String[] args) {
        DiGraph g = new DiGraph(6);
        g.addEdge(0,2,2,0,2,1,2,3,3,2,3,4,3,5);
        int s = 3;
        DepthFirstDirectedPaths dfs = new DepthFirstDirectedPaths(g, s);

        for (int v = 0; v < g.vertexNum(); v++) {
            if (dfs.hasPathTo(v)) {
                System.out.printf("%d to %d:  ", s, v);
                for (int x : dfs.pathTo(v)) {
                    if (x == s) {
                        System.out.print(x);
                    } else {
                        System.out.print("->" + x);
                    }
                }
                System.out.println();
            }

            else {
                System.out.printf("%d to %d:  not connected\n", s, v);
            }

        }
    }

}

可以利用深度优先搜索回答有向图中给定起点到某个顶点是否有路径的问题(可达性)。

上面构造了我们示例中的有向图,输出如下:

3 to 0:  3->2->0
3 to 1:  3->2->1
3 to 2:  3->2
3 to 3:  3
3 to 4:  3->4
3 to 5:  3->5

类似的,还可以得出有向图的最短路径。

package com.algorithms.graph;

import com.algorithms.queue.Queue;
import com.algorithms.stack.Stack;

/**
 * @author yjw
 * @date 2019/5/20/020
 */
public class BreadthFirstDirectedPaths {
    private boolean[] marked;
    /**
     * 到达当前顶点的最近顶点
     */
    private int[] edgeTo;
    private final int s;

    public BreadthFirstDirectedPaths(DiGraph g, int s) {
        marked = new boolean[g.vertexNum()];
        edgeTo = new int[g.vertexNum()];
        this.s = s;
        bfs(g, s);
    }

    private void bfs(DiGraph g, int s) {
        Queue<Integer> queue = new Queue<>();
        marked[s] = true;
        queue.enqueue(s);
        while (!queue.isEmpty()) {
            int v = queue.dequeue();
            /**
             * 将与v相邻的所有未被标记的顶点加入队列
             */
            for (int e: g.adj(v)) {
                if (!marked[e]) {
                    marked[e] = true;
                    edgeTo[e] = v;
                    queue.enqueue(e);
                }
            }
        }
    }

    public boolean hasPathTo(int v) {
        return marked[v];
    }

    public Iterable<Integer> pathTo(int v) {
        if (!hasPathTo(v)) {
            return null;
        }
        Stack<Integer> path = new Stack<>();
        /**
         * 从路径终点一步步寻找前一个顶点
         */
        for (int x = v; x != s ; x = edgeTo[x]) {
            path.push(x);
        }
        /**
         * 利用栈后进先出刚好可以顺序打印路径上所有顶点
         */
        path.push(s);
        return path;
    }

    public static void main(String[] args) {
        DiGraph g = new DiGraph(6);
        g.addEdge(0,2,2,0,2,1,2,3,3,2,3,4,3,5);
        int s = 0;
        BreadthFirstDirectedPaths bfs = new BreadthFirstDirectedPaths(g, s);

        for (int v = 0; v < g.vertexNum(); v++) {
            if (bfs.hasPathTo(v)) {
                System.out.printf("%d to %d:  ", s, v);
                for (int x : bfs.pathTo(v)) {
                    if (x == s) {
                        System.out.print(x);
                    } else {
                        System.out.print("->" + x);
                    }

                }
                System.out.println();
            }

            else {
                System.out.printf("%d to %d (-):  not connected\n", s, v);
            }

        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愤怒的可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值