美文网首页
图论(五)图的深度优先遍历DFS

图论(五)图的深度优先遍历DFS

作者: 小波同学 | 来源:发表于2022-04-04 23:39 被阅读0次

一、深度优先遍历

深度优先遍历,从初始访问结点出发,我们知道初始访问结点可能有多个邻接结点,深度优先遍历的策略就是首先访问第一个邻接结点,然后再以这个被访问的邻接结点作为初始结点,访问它的第一个邻接结点。总结起来可以这样说:每次都在访问完当前结点后首先访问当前结点的第一个邻接结点。

我们从这里可以看到,这样的访问策略是优先往纵向挖掘深入,而不是对一个结点的所有邻接结点进行横向访问。

具体算法表述如下:

  • 1、访问初始结点v,并标记结点v为已访问。
  • 2、查找结点v的第一个邻接结点w。
  • 3、若w存在,则继续执行4,否则算法结束。
  • 4、若w未被访问,对w进行深度优先遍历递归(即把w当做另一个v,然后进行步骤123)。
  • 5、查找结点v的w邻接结点的下一个邻接结点,转到步骤3。

二、邻接表进行深度优先遍历

2.1 构建数据结构

public class Graph {

    //顶点个数
    private int V;

    //边的条数
    private int E;

    //领接表的底层存储结构
    private TreeSet<Integer>[] adj;

}

2.2 通过该结构定义,我们构造一个图(无向图)

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 领接表, 目前只支持无向无权图
 */

public class Graph {

    //顶点个数
    private int V;

    //边的条数
    private int E;

    //领接表的底层存储结构
    private TreeSet<Integer>[] adj;

    public Graph(String filename){
        File file = new File(filename);
        try {
            Scanner scanner = new Scanner(file);
            V = scanner.nextInt();
            if(V < 0){
                throw new IllegalArgumentException("V must be non-negative");
            }
            adj = new TreeSet[V];
            //初始化领接表
            for (int i = 0; i < V; i++) {
                adj[i] = new TreeSet<>();
            }

            E = scanner.nextInt();
            if(E < 0){
                throw new IllegalArgumentException("E must be non-negative");
            }
            for (int i = 0; i < E; i++) {
                int a = scanner.nextInt();
                //校验顶点a是否合法
                validateVertex(a);

                int b = scanner.nextInt();
                //校验顶点b是否合法
                validateVertex(b);

                //校验是否是自环边
                if(a == b){
                    throw new IllegalArgumentException("Self Loop is Detected!");
                }
                //校验是否是平行边
                if(adj[a].contains(b)){
                    throw new IllegalArgumentException("Parallel Edges are Detected!");
                }
                adj[a].add(b);
                adj[b].add(a);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验顶点是否合法
     * @param v
     */
    private void validateVertex(int v){
        if(v < 0 || v >= V){
            throw new IllegalArgumentException("vertex " + v + " is invalid");
        }
    }

    /**
     * 获取顶点个数
     * @return
     */
    public int V(){
        return V;
    }

    /**
     * 获取边的条数
     * @return
     */
    public int E(){
        return E;
    }

    /**
     * 图中是否存在v到w的边
     * @param v
     * @param w
     * @return
     */
    public boolean hasEdge(int v, int w){
        //校验顶点v是否合法
        validateVertex(v);
        //校验顶点w是否合法
        validateVertex(w);
        return adj[v].contains(w);
    }

    /**
     * 返回和v相邻的顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adj(int v){
        //校验顶点v是否合法
        validateVertex(v);
        return adj[v];
    }

    /**
     * 返回顶点v的度
     * 顶点v的度(Degree)是指在图中与v相关联的边的条数
     * @param v
     * @return
     */
    public int degree(int v){
        //校验顶点v是否合法
        validateVertex(v);
        return adj[v].size();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("V = %d, E = %d\n", V, E));
        for (int v = 0; v < V; v++) {
            sb.append(String.format("%d : ", v));
            for (Integer w : adj[v]) {
                sb.append(String.format("%d ", w));
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}

2.3 邻接表的深度优先递归算法

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 图的深度优先遍历
 */

public class GraphDFS {

    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    //图的深度优先遍历前序遍历结果
    private List<Integer> pre = new ArrayList<>();

    //图的深度优先遍历后序遍历结果
    private List<Integer> post = new ArrayList<>();

    public GraphDFS(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                dfs(v);
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private void dfs(int v) {
        visited[v] = true;
        pre.add(v);
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                dfs(w);
            }
        }
        post.add(v);
    }

    public List<Integer> pre(){
        return pre;
    }

    public List<Integer> post(){
        return post;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        GraphDFS graphDFS = new GraphDFS(graph);
        System.out.println(graphDFS.pre());
        System.out.println(graphDFS.post());
    }
}

g1.txt

7 6
0 1
0 2
1 3
1 4
2 3
2 6

三、基于深度优先遍历的应用

3.1 求解联通分量

  • 1、图的联通分量个数
  • 2、判断两个顶点是否在同一个联通分量中
  • 3、图中不同的联通分量对应的顶点
/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解联通分量
 */

public class ConnectedGraph {

    private Graph G;

    //图的顶点是否已经被遍历过
    private int[] visited;

    //图的联通分量个数
    private Integer ccCount = 0;

    public ConnectedGraph(Graph G){
        this.G = G;
        visited = new int[G.V()];
        for (int i = 0; i < visited.length; i++) {
            visited[i] = -1;
        }
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(visited[v] == -1){
                dfs(v, ccCount);
                ccCount ++;
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private void dfs(int v, int ccId) {
        visited[v] = ccId;
        for (Integer w : G.adj(v)) {
            if(visited[w] == -1){
                dfs(w, ccId);
            }
        }
    }

    public Integer count(){
        return ccCount;
    }

    /**
     * 判断顶点v和w是否在同一个联通分量中
     * @param v
     * @param w
     * @return
     */
    public boolean isConnected(int v, int w){
        //校验顶点v是否合法
        G.validateVertex(v);
        //校验顶点w是否合法
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    /**
     * 返回图中不同的联通分量对应的顶点
     * @return
     */
    public List<Integer>[] components(){
        List<Integer>[] lists = new ArrayList[ccCount];
        for (int i = 0; i < ccCount; i++) {
            lists[i] = new ArrayList<>();
        }
        for (int v = 0; v < G.V(); v++) {
            lists[visited[v]].add(v);
        }
        return lists;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        ConnectedGraph ccGraph = new ConnectedGraph(graph);
        System.out.println(ccGraph.count());
        System.out.println(ccGraph.isConnected(0, 6));
        System.out.println(ccGraph.isConnected(0, 5));
        List<Integer>[] components = ccGraph.components();
        for (List<Integer> component : components) {
            System.out.println(component);
        }
    }
}

3.2 求解单源路径问题

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解单源路径问题
 */

public class SingleSourcePath {

    private Graph G;

    //源
    private int source;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 存储的是当前访问节点的前一个节点的值
     */
    private int[] pre;

    public SingleSourcePath(Graph G, int source){
        G.validateVertex(source);
        this.G = G;
        this.source = source;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        //pre数组的所有元素赋值为-1
        Arrays.fill(pre, -1);
        //单源路径问题,深度遍历从顶点s开始
        dfs(source, source);
    }

    /**
     * 图的深度优先遍历
     * @param v         当前节点
     * @param parent    当前节点的上一个节点
     */
    private void dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                dfs(w, v);
            }
        }
    }

    /**
     * 判断源s到顶点target是否可达
     * @param target
     * @return
     */
    public boolean isConnectedTo(int target){
        G.validateVertex(target);
        return visited[target];
    }

    /**
     * 源s到顶点target的路径
     * @param target
     * @return
     */
    public List<Integer> path(int target){
        List<Integer> result = new ArrayList<>();
        if(!isConnectedTo(target)){
            //源s到顶点target不可达, 直接返回空集合
            return result;
        }
        int cur = target;
        while(cur != source){
            result.add(cur);
            cur = pre[cur];
        }
        result.add(source);
        Collections.reverse(result);
        return result;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        SingleSourcePath ssPath = new SingleSourcePath(graph, 0);
        System.out.println("0 -> 6 : " + ssPath.path(6));
        System.out.println("0 -> 5 : " + ssPath.path(5));
    }
}

3.3 求解两点之间是否有路径问题

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解两点之间是否有路径问题
 */

public class Path {

    private Graph G;

    //源点
    private int source;

    //终止点
    private int target;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 存储的是当前访问节点的前一个节点的值
     */
    private int[] pre;

    public Path(Graph G, int source, int target){
        G.validateVertex(source);
        G.validateVertex(target);
        this.G = G;
        this.source = source;
        this.target = target;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        //pre数组的所有元素赋值为-1
        Arrays.fill(pre, -1);
        //单源路径问题,深度遍历从顶点s开始
        dfs(source, source);
    }

    /**
     * 图的深度优先遍历
     * @param v         当前节点
     * @param parent    当前节点的上一个节点
     */
    private boolean dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        if(v == target){
            return true;
        }
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(dfs(w, v)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断源s到顶点target是否可达
     * @return
     */
    public boolean isConnected(){
        return visited[target];
    }

    /**
     * 源s到顶点target的路径
     * @return
     */
    public List<Integer> path(){
        List<Integer> result = new ArrayList<>();
        if(!isConnected()){
            //源s到顶点target不可达, 直接返回空集合
            return result;
        }
        int cur = target;
        while(cur != source){
            result.add(cur);
            cur = pre[cur];
        }
        result.add(source);
        Collections.reverse(result);
        return result;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        Path path = new Path(graph, 0, 6);
        System.out.println("0 -> 6 : " + path.path());

        Path path2 = new Path(graph, 0, 1);
        System.out.println("0 -> 1 : " + path2.path());

        Path path3 = new Path(graph, 0, 5);
        System.out.println("0 -> 5 : " + path3.path());

    }
}

3.4 无向图的环检测

/**
 * @Author: huangyibo
 * @Date: 2022/4/9 16:16
 * @Description: 基于图的深度优先遍历、求解无向图的环检测问题
 */

public class CycleDetection {


    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    private boolean hasCycle = false;

    public CycleDetection(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                if(dfs(v, v)){
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    /**
     * 图的深度优先遍历
     * 从顶点V开始,判断图是否有环
     * @param v
     */
    private boolean dfs(int v, int parent) {
        visited[v] = true;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(dfs(w, v)){
                    return true;
                }
            }else if(w != parent){
                //表示图有环
                return true;
            }
        }
        return false;
    }

    /**
     * 图是否有环
     * @return
     */
    public boolean hasCycle(){
        return hasCycle;
    }

    public static void main(String[] args) {
        Graph graph1 = new Graph("src/main/resources/g1.txt");
        CycleDetection cycleDetection1 = new CycleDetection(graph1);
        System.out.println(cycleDetection1.hasCycle);

        Graph graph2 = new Graph("src/main/resources/g2.txt");
        CycleDetection cycleDetection2 = new CycleDetection(graph2);
        System.out.println(cycleDetection2.hasCycle);
    }
}

3.5 二分图的检测

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、二分图的检测
 */

public class BipartitionDetection {

    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 顶点的颜色数组
     */
    private int[] colors;

    //是否是二分图
    private boolean isBipartite = true;

    public BipartitionDetection(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        colors = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            colors[i] = -1;
        }
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                if(!dfs(v, 0)){
                    isBipartite = false;
                    break;
                }
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private boolean dfs(int v, int color) {
        visited[v] = true;
        colors[v] = color;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(!dfs(w, 1 - color)){
                    return false;
                }
            }else if(colors[w] == colors[v]){
                return false;
            }
        }
        return true;
    }

    /**
     * 是否是二分图
     * @return
     */
    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        BipartitionDetection bd = new BipartitionDetection(graph);
        System.out.println(bd.isBipartite());
    }
}

参考:
https://zhuanlan.zhihu.com/p/138073414

https://zhuanlan.zhihu.com/p/138073414

相关文章

网友评论

      本文标题:图论(五)图的深度优先遍历DFS

      本文链接:https://www.haomeiwen.com/subject/yymhsrtx.html