Graph Traversal BFS + DFS

Graph 的例子包括

  • City Map
  • Power Distribution Network
  • Water Distribution Network
  • Flight Network or Airports

相关概念:

  • Vertex / Vertices
  • Edge
  • Degree: the degree (or valency) of a vertex of a graph is the number of edges incident to the vertex, with loops counted twice
  • Directed / Undirected
  • Simple Graph: graphs with no parallel edges or self-loops
  • Connected: for any two vertices, there is a path between them
  • Strongly Connected: A directed graph is strongly connected if for any two vertices u and v of the graph , u reaches v and v reaches u
  • Forest: A forest is an undirected graph, all of whose connected components are trees; in other words, the graph consists of a disjoint union of trees. Equivalently, a forest is an undirected acyclic graph. As special cases, an empty graph, a single tree, and the discrete graph on a set of vertices (that is, the graph with these vertices that has no edges), are examples of forests.

Graph ADT:

  • field variables:
    • Collection of vertices
    • Collection of edges
  • numOfVertices()
  • numOfEdges()
  • getVertices(): return collection of vertices
  • getEdges(): return collection of edges
  • outDegree(Vertex v) / inDegree(Vertex v)
  • add(Vertex v)
  • add(Edge e, Vertex v, Vertex u)
  • removeVertex(Vertex v)
  • removeEdge(Edge e)

Graph 的若干总表达方式:

  • Edge List
  • Adjacency List:
    • getEdge(Vertex v, Vertex u): O( min ( deg(v), deg(u) ) )
  • Adjacency Map
  • Adjacency Matrix


public class GraphNode {
    int val;
    List<GraphNode> neighbors;

    public GraphNode(int val) {
        this.val = val;
        this.neighbors = new ArrayList<GraphNode>();
    }
}

DFS (O(2^n), O(n!)) (思想:构建搜索树+判断可行性)

  1. Find all possible solutions
  2. Permutations / Subsets

BFS (O(m), O(n))

  1. Graph traversal (每个点只遍历一次)
  2. Find shortest path in a simple graph

Graph BFS

HashSet<GraphNode> visited is for:

  1. Avoid infinite loop in Graph circle
  2. 消除冗余计算
public List<List<Integer>> bfsGraph(GraphNode root) {
    List<List<Integer>> res = new ArrayList<>();

    if (root == null) {
        return res;
    }

    Queue<GraphNode> queue = new LinkedList<>();
    Set<GraphNode> visited = new HashSet<>();
    queue.offer(root);
    visited.add(root);
    // int level = 0;

    while (!queue.isEmpty()) {
        // level++;
        ArrayList<Integer> layer = new ArrayList<>(queue.size());
        int size = queue.size();
        while (size > 0) {
            GraphNode node = queue.poll();
            layer.add(node.val);
            for (GraphNode neighbor: node.neighbors) {
                if (!visited.contains(neighbor)) {
                    queue.offer(neighbor);
                    visited.add(neighbor);
                }
            }
            size--;
        }
        res.add(layer);
    }

    return res;
}

comparing Binary Tree BFS traversal

public List<List<Integer>> bfsTree(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();

    if (root == null) {
        return res;
    }

    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        ArrayList<Integer> layer = new ArrayList<Integer>(queue.size());
        int size = queue.size();
        
        while(size > 0) {
            TreeNode node = queue.poll();
            layer.add(node.val);

            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }

            size--;
        }
        res.add(layer);
    }

    return res;
}

BFS 易于计算 minimum level for each node in Graph or Tree.

BFS 并不适于计算 maximum level for each GraphNode. 可能需要 max level 运算的题目: Topological Sorting. 此题题解:GeeksForGeeks, 尚未细看。

Graph BFS 也不适用于判断 Graph 中是否存在 circle,因为 visited Hash 已经将 circle 过滤处理了。DFS 应该更适用于判断 circle。



Graph DFS

使用 DFS 判断 Graph 中是否存在 circle:

public boolean hasCircle(GraphNode root) {
    if (root == null) {
        false;
    }

    Set<GraphNode> visited = new HashSet<>();

    return dfsGraph(root, visited);
}

private boolean dfsGraph(GraphNode root, Set<GraphNode> visited) {
    visited.add(root);

    for (GraphNode neighbor: root.neighbors) {
        if (visited.contains(neighbor)) {
            return true;
        }
        dfsGraph(neighbor, visited);
    }

    visited.remove(root);
    return false;
}

上面的实现方式存在冗余计算。这里的visited Hash实际上是 path. 优化的实现方法:

public boolean hasCircle(GraphNode root) {
   if (root == null) {
       false;
   }

   Set<GraphNode> path = new HashSet<>();
   Set<GraphNode> visited = new HashSet<>();

   return dfsGraph(root, path, visited);
}

private boolean dfsGraph(GraphNode root, Set<GraphNode> path, Set<GraphNode> visited) {
   visited.add(root);
   path.add(root);

   for (GraphNode neighbor: root.neighbors) {
       if (path.contains(neighbor)) {
           return true;
       }
       if (!visited.contains(neighbor)) {
           dfsGraph(neighbor, path);
       }
   }

   path.remove(root);
   return false;
}

题解中的 path: 1. add current node; 2. dfs neighbors; 3. remove current nodeBackTracking 的经典实现方式。实际上 BackTracking 也正是使用 DFS 来实现的。

以上基本就是 Graph DFS 的实现方式,不同于 Tree DFS 之处:

  • Graph DFS 只有 preorder 和 postorder 形式,inorder 并没有多大意义。
  • Graph DFS 同 Graph BFS一样,可以使用 visited Hash来消除冗余计算,防止 circle 死循环。
  • 如果涉及到 GraphNode depth,visited Hash是不可以使用的,因为需要遍历所有path,不同的path 对同一个 GraphNode depth 产生不一样的值。这种情况,可以使用 path Hash来防止死循环。

Problems Solved with Graph DFS

1) For an unweighted graph, DFS traversal of the graph produces the minimum spanning tree and all pair shortest path tree.

2) Detecting cycle in a graph
A graph has cycle if and only if we see a back edge during DFS. So we can run DFS for the graph and check for back edges.

3) Path Finding
We can specialize the DFS algorithm to find a path between two given vertices.

4) Topological Sorting
Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles, data serialization, and resolving symbol dependencies in linkers.

5) To test if a graph is bipartite
We can augment either BFS or DFS when we first discover a new vertex, color it opposited its parents, and for each other edge, check it doesn’t link two vertices of the same color. The first vertex in any connected component can be red or black! See this for details.

6) Finding Strongly Connected Components of a graph A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex. (See this for DFS based algo for finding Strongly Connected Components)

7) Solving puzzles with only one solution, such as mazes. (DFS can be adapted to find all solutions to a maze by only including nodes on the current path in the visited set.)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,723评论 0 33
  • 课程介绍 先修课:概率统计,程序设计实习,集合论与图论 后续课:算法分析与设计,编译原理,操作系统,数据库概论,人...
    ShellyWhen阅读 2,252评论 0 3
  • 一、动态规划 找到两点间的最短路径,找最匹配一组点的线,等等,都可能会用动态规划来解决。 参考如何理解动态规划中,...
    小碧小琳阅读 24,700评论 2 20
  • 不为苦而悲,不受宠而欢。
    晚风吻尽你阅读 264评论 0 0
  • 昨晚听着音乐睡着了,今天怎么都没力气起来,平时七点多起床,今天一直睡到十点多,还头疼,浑身没力。心里也提不起劲。我...
    觉知中的帆阅读 102评论 0 0