深度优先搜索是一个针对图和树的遍历算法。早在19世纪就被用于解决迷宫问题。
对于下面的树而言,DFS方法首先从根节点1开始,其搜索节点顺序是1,2,3,4,5,6,7,8(假定左分枝和右分枝中优先选择左分枝)。
DFS的非递归实现方式相比于BFS应该说大同小异,只是把queue换成了stack而已,stack具有后进先出LIFO(Last Input First Output)的特性,DFS的操作步骤如下:
下面结合一个图(graph)的实例,说明DFS的工作过程和原理:
12、当前stack栈顶的节点是9,没有尚未遍历的邻接点,将节点9弹出,依次类推,栈中剩余节点8、6、4、3、2、1都没有尚未遍历的邻接点,都将弹出,最后栈为空。
13、DFS遍历完成。
public class Graph {
//顶点个数
private int V;
//边的条数
private int E;
//领接表的底层存储结构
private TreeSet<Integer>[] adj;
}
/**
* @Author: huangyibo
* @Date: 2022/3/28 1:02
* @Description: 领接表, 目前只支持无向无权图
*/
public class Graph {
//顶点个数
private int V;
//边的条数
private int E;
//领接表的底层存储结构
private TreeSet<Integer>[] adj;
public Graph(String filename){
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
V = scanner.nextInt();
if(V < 0){
throw new IllegalArgumentException("V must be non-negative");
}
adj = new TreeSet[V];
//初始化领接表
for (int i = 0; i < V; i++) {
adj[i] = new TreeSet<>();
}
E = scanner.nextInt();
if(E < 0){
throw new IllegalArgumentException("E must be non-negative");
}
for (int i = 0; i < E; i++) {
int a = scanner.nextInt();
//校验顶点a是否合法
validateVertex(a);
int b = scanner.nextInt();
//校验顶点b是否合法
validateVertex(b);
//校验是否是自环边
if(a == b){
throw new IllegalArgumentException("Self Loop is Detected!");
}
//校验是否是平行边
if(adj[a].contains(b)){
throw new IllegalArgumentException("Parallel Edges are Detected!");
}
adj[a].add(b);
adj[b].add(a);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 校验顶点是否合法
* @param v
*/
private void validateVertex(int v){
if(v < 0 || v >= V){
throw new IllegalArgumentException("vertex " + v + " is invalid");
}
}
/**
* 获取顶点个数
* @return
*/
public int V(){
return V;
}
/**
* 获取边的条数
* @return
*/
public int E(){
return E;
}
/**
* 图中是否存在v到w的边
* @param v
* @param w
* @return
*/
public boolean hasEdge(int v, int w){
//校验顶点v是否合法
validateVertex(v);
//校验顶点w是否合法
validateVertex(w);
return adj[v].contains(w);
}
/**
* 返回和v相邻的顶点
* @param v
* @return
*/
public Iterable<Integer> adj(int v){
//校验顶点v是否合法
validateVertex(v);
return adj[v];
}
/**
* 返回顶点v的度
* 顶点v的度(Degree)是指在图中与v相关联的边的条数
* @param v
* @return
*/
public int degree(int v){
//校验顶点v是否合法
validateVertex(v);
return adj[v].size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("V = %d, E = %d\n", V, E));
for (int v = 0; v < V; v++) {
sb.append(String.format("%d : ", v));
for (Integer w : adj[v]) {
sb.append(String.format("%d ", w));
}
sb.append("\n");
}
return sb.toString();
}
}
/**
* @Author: huangyibo
* @Date: 2022/3/28 1:02
* @Description: 图的深度优先遍历, 非递归方式
*/
public class GraphDFS {
private Graph G;
/**
* 图的顶点是否已经被遍历过
*/
private boolean[] visited;
//图的深度优先遍历结果
private List<Integer> order = new ArrayList<>();
public GraphDFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
//循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
for (int v = 0; v < G.V(); v++) {
if(!visited[v]){
dfs(v);
}
}
}
/**
* 图的深度优先遍历, 非递归方式
* @param source
*/
private void dfs(int source) {
Stack<Integer> stack = new Stack<>();
//将源结点压入栈顶
stack.push(source);
//标记为已访问
visited[source] = true;
//如果栈不为空
while(!stack.isEmpty()){
Integer v = stack.pop();
//当前出栈顶点添加到图的深度优先遍历结果集
order.add(v);
//遍历顶点V的相邻顶点
for (Integer w : G.adj((v))) {
//如果没有遍历过
if(!visited[w]){
//顶点w压入栈顶
stack.push(w);
//标记w为已访问
visited[w] = true;
}
}
}
}
/**
* 图的深度优先遍历结果集
* @return
*/
public List<Integer> order(){
return order;
}
public static void main(String[] args) {
Graph graph = new Graph("src/main/resources/g1.txt");
GraphDFS graphDFS = new GraphDFS(graph);
System.out.println(graphDFS.order());
}
}
7 6
0 1
0 2
1 3
1 4
2 3
2 6
参考:
https://blog.csdn.net/saltriver/article/details/54429068