这两天刷了几道OJ上的搜索题,主要是深度优先搜索和广度优先搜索,简单的总结如下,
深度优先搜索法(Depth-first Search):
Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph.One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.(Definition in Wiki).
深度优先搜索属于盲目搜索(uniformed search),一般可以利用堆栈的方式实现。其范例见下面的图,它以A为根节点,搜索结果为A,B,E,F,D,C,G
伪代码为:
procedure dfs(vertex v) { mark v as visited for each w adjacent to v { if w unvisited { dfs(w) } } }
广度优先搜索法(Breadth-first Search)
Breadth-first search (BFS) is a strategy for searching in a graph.The BFS begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on.(Definition in Wiki)
广度优先搜索也属于盲目搜索的方法,一般使用队列实现。其范例见下图:
伪代码为:
procedure BFS(vertex s) { create a queue Q enqueue s onto Q mark s as visited while Q is not empty { dequeue a vertex from Q into v for each w adjacent to v { if w unvisited { mark w as visited enqueue w onto Q } } } }
注意一点:深搜通常有递归,而广搜一个循环就搞定了。