每个节点访问一次,每条边访问一次,时间复杂度O(V+E)
public class DFS { public static int timer = 0; public static void dfs(Graph g, Vertex v){ assert(true); if(v.color != Vertex.WHITE){ return; } System.out.print(v.id + " "); v.color = Vertex.GRAY; v.start_time = timer++; for(int i=0; i<g.count_vertex; i++){ if(g.adjMatrix[v.id][i] > 0){ g.vertexs[i].parent = v; dfs(g, g.vertexs[i]); } } v.color = Vertex.BLACK; v.end_time = timer++; } /** * @param args */ public static void main(String[] args) { //如果是无向连通图,一次遍历可以读完,只有一棵树 Graph g = Graph.createNoDirectedGraph(8, "dfs.txt"); g.printGraph(); DFS.timer = 0; DFS.dfs(g, g.vertexs[5]); System.out.println(); for(int i=0; i<g.count_vertex; i++){ System.out.print(g.vertexs[i].start_time + " " + g.vertexs[i].end_time + " : "); } System.out.println(); for(int i=0; i<g.count_vertex; i++){ System.out.print(g.vertexs[i].parent.id + " "); } System.out.println(); //如果有向连通图,一次读不完,多次读,形成森林 // Graph g = Graph.createDirectedGraph(8, "dfs.txt"); // g.printGraph(); // for(int i=0; i<g.count_vertex; i++){ // if(g.vertexs[i].color == Vertex.WHITE){ // DFS.dfs(g, g.vertexs[i]); // } // } } }