图——深度优先搜索(Graph - Depth First Search)

深度优先搜索(DFS)详解
深度优先搜索(DFS)是一种遍历或搜索树或图数据结构的算法。从根节点开始(对于图来说,选择任意节点作为根),沿着每个分支尽可能深入地探索,再回溯。本文介绍了DFS的基本概念、示例、使用栈进行遍历的过程、搜索树的绘制,以及DFS的时间复杂度。同时,探讨了如何利用DFS解决图是否连通、是否存在环以及如何判断有向无环图等问题。

简介(Introduction)
Depth-first search(DFS) is an algorithm for traversing or searching tree or graph data structure. One starts at the root(selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

示例(Example)
这里写图片描述
DFS order: a, b, d, e, c, f, g.

检索栈(The Traversal Stack)
We can use a traversal stack to track where we are in overall process.
这里写图片描述

Push order: a, b, d, e, c, f, g.
Pop order: e, d, b, c, a, g, f.

Push nodes into stack when visiting. Pop nodes as all of its neighbours are visited.

Actually, pushing-order gives us node-visiting order which is DFS order. Poping-order gives us backtracking path.

搜索树(DFS Tree)
We can draw DFS tree(forest) to depict DF-traversal.
这里写图片描述

算法(Algorithm Pseudocode)

function DFS(<V, E>)
    mark each node in V with 0
    count ⟵ 0
    for each v in V do
        if v is marked with 0 then
            DFSExplore(v)

function DFSExplore(v)
    count ⟵ count + 1
    mark v with count
    for each edge (v, w) do
        if w is marked with 0 then
            DFSExplore(w)

时间复杂度(Time Complexity)
We can implement marking nodes by maintaining an array mark[] indexed by V. For example, “mark v with count” = “mark[v] = count”. The value of count represents the order number visited. For instance, “mark[v] = 3”. It means node v is the third node visited.

If we use adjacency matrix to represent a graph. The time for finding each edge (v, w) is |V|^2. Hence the complexity of graph traversal is (|V| + |V|^2), which is Θ(|V|^2).

If using adjacency list, for each v we traverse the list adj[v] to find all its neighbour. It will take |E| times. overall, its time complexity is Θ(|V| + |E|).

问题(Questions)
Based on the algorithm, answer those following questions.
1. How to decide whether a graph is connected?
2. how to decide whether a graph has a cycle?
3. In terms of DFS tree(forest), how can we tell if we have traversed a dag.

写在后面的话(PS)
DFS is a great tree traversal and searching technique.

Ask yourself, what practical problems can we solve using DFS? Give specific example.

Welcome questions always and forever.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值