Graph Traversal BFS + DFS

Graph 的例子包括

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

相關(guān)概念:

  • 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 的若干總表達(dá)方式:

  • 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!)) (思想:構(gòu)建搜索樹+判斷可行性)

  1. Find all possible solutions
  2. Permutations / Subsets

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

  1. Graph traversal (每個(gè)點(diǎn)只遍歷一次)
  2. Find shortest path in a simple graph

Graph BFS

HashSet<GraphNode> visited is for:

  1. Avoid infinite loop in Graph circle
  2. 消除冗余計(jì)算
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 易于計(jì)算 minimum level for each node in Graph or Tree.

BFS 并不適于計(jì)算 maximum level for each GraphNode. 可能需要 max level 運(yùn)算的題目: Topological Sorting. 此題題解:GeeksForGeeks, 尚未細(xì)看寸潦。

Graph BFS 也不適用于判斷 Graph 中是否存在 circle,因?yàn)?visited Hash 已經(jīng)將 circle 過濾處理了咖为。DFS 應(yīng)該更適用于判斷 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;
}

上面的實(shí)現(xiàn)方式存在冗余計(jì)算吓歇。這里的visited Hash實(shí)際上是 path. 優(yōu)化的實(shí)現(xiàn)方法:

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 的經(jīng)典實(shí)現(xiàn)方式。實(shí)際上 BackTracking 也正是使用 DFS 來實(shí)現(xiàn)的。

以上基本就是 Graph DFS 的實(shí)現(xiàn)方式粉寞,不同于 Tree DFS 之處:

  • Graph DFS 只有 preorder 和 postorder 形式昌执,inorder 并沒有多大意義烛亦。
  • Graph DFS 同 Graph BFS一樣,可以使用 visited Hash來消除冗余計(jì)算懂拾,防止 circle 死循環(huán)煤禽。
  • 如果涉及到 GraphNode depth,visited Hash是不可以使用的岖赋,因?yàn)樾枰闅v所有path檬果,不同的path 對(duì)同一個(gè) GraphNode depth 產(chǎn)生不一樣的值。這種情況唐断,可以使用 path Hash來防止死循環(huán)选脊。

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.)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市脸甘,隨后出現(xiàn)的幾起案子恳啥,更是在濱河造成了極大的恐慌,老刑警劉巖丹诀,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件钝的,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡铆遭,警方通過查閱死者的電腦和手機(jī)硝桩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枚荣,“玉大人碗脊,你說我怎么就攤上這事¢献保” “怎么了衙伶?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)害碾。 經(jīng)常有香客問我痕支,道長(zhǎng),這世上最難降的妖魔是什么蛮原? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任卧须,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘花嘶。我一直安慰自己笋籽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布椭员。 她就那樣靜靜地躺著车海,像睡著了一般。 火紅的嫁衣襯著肌膚如雪隘击。 梳的紋絲不亂的頭發(fā)上侍芝,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音埋同,去河邊找鬼州叠。 笑死,一個(gè)胖子當(dāng)著我的面吹牛凶赁,可吹牛的內(nèi)容都是我干的咧栗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼虱肄,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼致板!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起咏窿,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤斟或,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后集嵌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缕粹,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年纸淮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片亚享。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咽块,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出欺税,到底是詐尸還是另有隱情侈沪,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布晚凿,位于F島的核電站亭罪,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏歼秽。R本人自食惡果不足惜应役,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧箩祥,春花似錦院崇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至蕉陋,卻和暖如春捐凭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背凳鬓。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工茁肠, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人村视。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓官套,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蚁孔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子奶赔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,745評(píng)論 0 33
  • 課程介紹 先修課:概率統(tǒng)計(jì)杠氢,程序設(shè)計(jì)實(shí)習(xí)站刑,集合論與圖論 后續(xù)課:算法分析與設(shè)計(jì),編譯原理鼻百,操作系統(tǒng)绞旅,數(shù)據(jù)庫(kù)概論,人...
    ShellyWhen閱讀 2,290評(píng)論 0 3
  • 一、動(dòng)態(tài)規(guī)劃 找到兩點(diǎn)間的最短路徑勺爱,找最匹配一組點(diǎn)的線晃琳,等等,都可能會(huì)用動(dòng)態(tài)規(guī)劃來解決琐鲁。 參考如何理解動(dòng)態(tài)規(guī)劃中卫旱,...
    小碧小琳閱讀 24,879評(píng)論 2 20
  • 不為苦而悲,不受寵而歡围段。
    晚風(fēng)吻盡你閱讀 269評(píng)論 0 0
  • 昨晚聽著音樂睡著了顾翼,今天怎么都沒力氣起來,平時(shí)七點(diǎn)多起床奈泪,今天一直睡到十點(diǎn)多适贸,還頭疼灸芳,渾身沒力。心里也提不起勁取逾。我...
    覺知中的帆閱讀 107評(píng)論 0 0