Graph DFS / BFS traverse

Graph Representation & Build:
http://www.jianshu.com/p/857e7cc63077

无向图时 避免向回访问前驱的方式:
(1) adj_list中remove掉前驱
(2) visited数组

DFS (recursive):
a(recommended) 最好在递归前就check next是否visited/出界,如果没有visit/出界过,再递归去visit next,递归内部置visited = true; 这样在递归内部开始时就不用check是否visited,因为一定是unvisited的。
当然也可以在递归前就把next置为visited。

b或是写法简单的:直接dfs,但每次进入递归再检查是否visited/出界。
a

DFSearch(start);

private void DFSearch(Vertex v) {
    v.setVisited(true);
    // do something with this node
    something();
    for (Edge e : v.getEdges()) {
            Vertex neighbor = e.getTarget();
            if (!neighbor.isVisited())
                DFSearch(neighbor);
        }
    }

b

DFSearch(start);

private void DFSearch(Vertex v) {
    if(v.isVisited) return;
    v.setVisited(true);
    // do something with this node
    something();
    for (Edge e : v.getEdges()) {
            Vertex neighbor = e.getTarget();
            DFSearch(neighbor);
        }
    }

DFS (stack):
neighbors在放入stack前就check其是否被visited,如果没有visit过,说明是新的结点:则将neighbors放入stack,并将其visited[neighbors]置为true,待下次处理。
这样在拿出的时候一定是没有visit过的,就不用check了。

Deque> stack = new ArrayDeque>();

stack.push(source);
source.setVisited(true);

while (!stack.isEmpty()) {
    node = stack.pop();
            
    // do some thing with node
    something();

    for (Edge e : source.getEdges()) {
        Vertex neighbor = e.getTarget();
        if (neighbor.isVisited())
            continue;
        stack.push(neighbor);
        target.setVisited(true);
    }
}

BFS (queue): 可以避免dfs的stack overflow
neighbors在放入queue前就check其是否被visited,如果没有visit过,说明是新的结点:则将neighbors放入queue,并将其visited[neighbors]置为true,待下次处理。
这样在拿出的时候一定是没有visit过的,就不用check了。

Queue> queue = new LinkedList>();

queue.add(source);
source.setVisited(true);

while (!queue.isEmpty()) {
    node = queue.poll();
            
    // do some thing with node
    something();

    for (Edge e : source.getEdges()) {
        Vertex neighbor = e.getTarget();
        if (neighbor.isVisited())
            continue;
        queue.add(neighbor);
        target.setVisited(true);
    }
}

General Graph:
133 Clone Graph: 图的复制 (DFS + HashMap)
207 Course Schedule http://www.jianshu.com/p/8665248b4458
210 Course Schedule II http://www.jianshu.com/p/96841bf6f167
261 Graph Valid Tree www.jianshu.com/p/ffd3a82e0388
323 Number of Connected Components in an Undirected
Graph http://www.jianshu.com/p/bb815473eb87
332 Reconstruct Itinerary http://www.jianshu.com/p/443d7133a7ad
310 Minimum Height Trees www.jianshu.com/p/b0ff2e41d94d
269题 Alien Dictionary

  1. Evaluate Division: 无向图 dfs 搜索
  2. Sequence Reconstruction: 拓扑排序

Square grid:
130 Surrounded Regions http://www.jianshu.com/p/0ff5fb9466a9
200 Number of Islands: http://www.jianshu.com/p/f834dbd46dd3
79 Word Search http://www.jianshu.com/p/0da28fc9cb3e
286 Walls and Gates www.jianshu.com/p/7e0d87d8e8b3

Djikstra Shortest path
https://leetcode.com/problems/network-delay-time/

你可能感兴趣的:(Graph DFS / BFS traverse)