如何使用DFS的迭代版本检测有向图中的循环?

时间:2017-09-30 19:00:17

标签: algorithm graph-algorithm depth-first-search

在递归DFS中,我们可以通过将节点着色为WHITEGRAYBLACK来检测周期,如解释here

如果在DFS搜索期间遇到GRAY节点,则存在循环。

我的问题是:在DFS的这个迭代版本中,我何时将节点标记为GRAYBLACK? (来自维基百科)

    1  procedure DFS-iterative(G,v):
    2      let S be a stack
    3      S.push(v)
    4      while S is not empty
    5          v = S.pop()
    6          if v is not labeled as discovered:
    7              label v as discovered
    8              for all edges from v to w in G.adjacentEdges(v) do 
    9                  S.push(w)

4 个答案:

答案 0 :(得分:4)

如果您正在输入或退出信息,则可以选择将每个节点两次推送到堆栈。从堆栈中弹出节点时,检查是否正在进入或退出。如果输入颜色为灰色,请将其再次叠加并前往邻居。如果退出,只需将其着色为黑色。

这是一个简短的Python演示,它在一个简单的图中检测一个循环:

from collections import defaultdict

WHITE = 0
GRAY = 1
BLACK = 2

EDGES = [(0, 1), (1, 2), (0, 2), (2, 3), (3, 0)]

ENTER = 0
EXIT = 1

def create_graph(edges):
    graph = defaultdict(list)
    for x, y in edges:
        graph[x].append(y)

    return graph

def dfs_iter(graph, start):
    state = {v: WHITE for v in graph}
    stack = [(ENTER, start)]

    while stack:
        act, v = stack.pop()

        if act == EXIT:
            print('Exit', v)
            state[v] = BLACK
        else:
            print('Enter', v)
            state[v] = GRAY
            stack.append((EXIT, v))
            for n in graph[v]:
                if state[n] == GRAY:
                    print('Found cycle at', n)
                elif state[n] == WHITE:
                    stack.append((ENTER, n))

graph = create_graph(EDGES)
dfs_iter(graph, 0)

输出:

Enter 0
Enter 2
Enter 3
Found cycle at 0
Exit 3
Exit 2
Enter 1
Exit 1
Exit 0

答案 1 :(得分:4)

您可以简单地通过不立即弹出堆栈元素来做到这一点。 对于每次迭代,请执行v = stack.peek(),如果vWhite,请将其标记为Grey,然后继续探索其邻居。

但是,如果v是灰色,则表示您在堆栈中第二次遇到v,并且已经完成了探索。将其标记为Black,然后继续循环。

这是修改后的代码的样子:

procedure DFS-iterative(G,v):
    let S be a stack
    S.push(v)
    while S is not empty
        v = S.peek()
        if v is not labeled as Grey:
            label v as Grey
            for all edges from v to w in G.adjacentEdges(v) do
                if w is labeled White do
                    S.push(w)
                elif w is labeled Grey do
                    return False    # Cycle detected
                                    # if w is black, it's already explored so ignore
        elif v is labeled as Grey:
            S.pop()                 # Remove the stack element as it has been explored
            label v as Black

如果您使用visited列表标记所有访问过的节点,并使用另一个recStack标记跟踪当前正在探索的节点的列表,那么您可以做的就是,而不是弹出元素,只需执行stack.peek()。如果未访问该元素(这意味着您是第一次在堆栈中遇到该元素),只需在Truevisited中将其标记为recStack并探索其子元素。 / p>

但是,如果peek()值已经被访问,则意味着您正在结束对该节点的探索,因此只需将其弹出并再次将其recStack设置为False。

答案 2 :(得分:1)

我已解决此问题,作为此Leetcode问题的解决方案-https://leetcode.com/problems/course-schedule/

我已经用Java实现了它-使用带有颜色的递归DFS,使用访问数组的递归DFS,使用indegree并计算拓扑排序的迭代DFS和BFS。

class Solution {
    //prereq is the edges and numCourses is number of vertices
    public boolean canFinish(int numCourses, int[][] prereq) {

        //0 -> White, -1 -> Gray, 1 -> Black
        int [] colors = new int[numCourses];
        boolean [] v = new boolean[numCourses];
        int [] inDegree = new int[numCourses];
        Map<Integer, List<Integer>> alMap = new HashMap<>();
        
        for(int i = 0; i < prereq.length; i++){
            int s = prereq[i][0];
            int d = prereq[i][1];
            alMap.putIfAbsent(s, new ArrayList<>());
            alMap.get(s).add(d);
            inDegree[d]++;
        }
        // if(hasCycleBFS(alMap, numCourses, inDegree)){
        //     return false;
        // }
        for(int i = 0; i < numCourses; i++){
            if(hasCycleDFS1(i, alMap, colors)){
            // if(hasCycleDFS2(i, alMap, v)){
            //if(hasCycleDFSIterative(i, alMap, colors)){
                return false;
            }
       }
        return true;
    }
    //12.48
    boolean hasCycleBFS(Map<Integer, List<Integer>> alMap, int numCourses, int [] inDegree){
        //short [] v = new short[numCourses];
        Deque<Integer> q = new ArrayDeque<>();
        for(int i = 0; i < numCourses; i++){
            if(inDegree[i] == 0){
                q.offer(i);
            }
        }
        List<Integer> tSortList = new ArrayList<>();
        while(!q.isEmpty()){
            int cur = q.poll();
            tSortList.add(cur);
            //System.out.println("cur = " + cur);
            
            if(alMap.containsKey(cur)){
                for(Integer d: alMap.get(cur)){
                    //System.out.println("d = " + d);
                    // if(v[d] == true){
                    //     return true;
                    // }
                    inDegree[d]--;
                    if(inDegree[d] == 0){
                        q.offer(d);
                    }
                }
            }
        }
       
        return tSortList.size() == numCourses?  false:  true;
    }
    // inspired from - https://leetcode.com/problems/course-schedule/discuss/58730/Explained-Java-12ms-Iterative-DFS-solution-based-on-DFS-algorithm-in-CLRS
    //0 -> White, -1 -> Gray, 1 -> Black
    boolean hasCycleDFSIterative(int s, Map<Integer, List<Integer>> alMap, int [] colors){
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(s);
        while(!stack.isEmpty()){
            int cur = stack.peek();
            if(colors[cur] == 0){
                colors[cur] = -1;
                if(alMap.containsKey(cur)){
                    for(Integer d: alMap.get(cur)){
                        if(colors[d] == -1){
                            return true;
                        }
                        if(colors[d] == 0){
                            stack.push(d);
                        }
                    }
                }
            }else if (colors[cur] == -1 || colors[cur] == 1){
                    colors[cur] = 1;
                    stack.pop();
            }
        }

        return false;
    }
    
    boolean hasCycleDFS1(int s, Map<Integer, List<Integer>> alMap, int [] colors){
        // if(v[s] == true){
        //     return true;
        // }
        colors[s] = -1;
        if(alMap.containsKey(s)){
            for(Integer d: alMap.get(s)){
                //grey vertex
                if(colors[d] == -1){
                    return true;
                }
                if(colors[d] == 0 && hasCycleDFS1(d, alMap, colors)){
                    return true;
                }
            }
        }
        colors[s] = 1;
        return false;
    }
    
    // not efficient because we process black vertices again 
    boolean hasCycleDFS2(int s, Map<Integer, List<Integer>> alMap, boolean [] v){
        // if(v[s] == true){
        //     return true;
        // }
        v[s] = true;
        if(alMap.containsKey(s)){
            for(Integer d: alMap.get(s)){
                if(v[d] == true || hasCycleDFS2(d, alMap, v)){
                    return true;
 
                }
            }
        }
        v[s] = false;
        return false;
    }
    
}

答案 3 :(得分:0)

DFS中,分支的末尾是没有孩子的节点,这些节点是黑色。然后检查这些节点的父节点。如果父母没有Gray孩子,则黑色。同样,如果继续为节点设置黑色,则所有节点的颜色都会变为黑色。

例如,我想在下面的图表中执行DFS

DFS Example

DFSu开始,访问u -> v -> y -> xx没有孩子,您应该将此节点的颜色更改为黑色

然后根据x返回访问路径中的discovery time的父级。因此x的父级是yy没有Gray颜色的子项,因此您应将此节点的颜色更改为黑色