Breadth first search: the timing of checking visitation status

后端 未结 2 1611
北荒
北荒 2021-02-01 07:43

In a breadth first search of a directed graph (cycles possible), when a node is dequeued, all its children that has not yet been visited are enqueued, and the process continues

2条回答
  •  礼貌的吻别
    2021-02-01 08:34

    DFS checks whether a node has been visited when dequeing because it may have been visited at a "deeper" level. For example:

    A--B--C--E
    |     |
    -------
    

    If we start at A, then B and C will be put on the stack; assume we put them on the stack so B will be processed first. When B is now processed, we want to go down to C and finally to E, which would not happen if we marked C as visited when we discovered it from A. Now once we proceed from B, we find the yet unvisited C and put it on the stack a second time. After we finished processing E, all C entries on the stack need to be ignored, which marking as visited will take care of for us.


    As @PeterdeRivaz said, for BFS it's not a matter of correctness, but efficiency whether we check nodes for having been visited when enqueuing or dequeuing.

提交回复
热议问题