1. 树的深度优先遍历与图的深度优先遍历对比
2. 代码实现(递归版)
import java.util.ArrayList;
public class GraphDFS {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> order = new ArrayList<>();
GraphDFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
//解决非连通图的遍历问题
for (int v = 0; v < G.V(); v++) {
if(!visited[v])
dfs(v);
}
//dfs(0);
}
private void dfs(int v){
visited[v] = true;
order.add(v);
for(int w:G.adj(v)){
if(!visited[w])
dfs(w);
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args) {
Graph g = new Graph("g_3.txt");
GraphDFS graphDFS = new GraphDFS(g);
System.out.println(graphDFS.order());
}
}
时间复杂度:O(V+E)
3. 代码实现(非递归版)
import java.util.ArrayList;
import java.util.Stack;
public class GraphDFS_non_recursion {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> order = new ArrayList<>();
GraphDFS_non_recursion(Graph G){
this.G = G;
visited = new boolean[G.V()];
//解决非连通图的遍历问题
for (int v = 0; v < G.V(); v++) {
if(!visited[v])
dfs(v);
}
//dfs(0);
}
private void dfs(int v){
Stack<Integer> stack = new Stack<>();
stack.push(v);
visited[v] = true;
while(!stack.empty()){
int cur = stack.pop();
order.add(cur);
for(int w:G.adj(cur)){
if(!visited[w]){
stack.push(w);
visited[w] = true;
}
}
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args) {
Graph g = new Graph("g_3.txt");
GraphDFS_non_recursion graphDFSnr = new GraphDFS_non_recursion(g);
System.out.println(graphDFSnr.order());
}
}
- 注:本系列参考玩转算法系列–图论精讲