Package Cn.xf.algorithm.ch03;import org.junit.test;/** * Depth-First traversal * @author xiaof * */public class DFS {public void Deepfirs Tsearch (int graph[][], char points[], int marks[]) {//bar all points are set to 0, indicating that no access has been done for (int i = 0; i < marks.length; ++i) {Marks[i] = 0;} Traverse all nodes to access for (int i = 0; i < points.length; ++i) {//To determine if this node has not been accessed if (marks[i] = 0) {//system.out.println ("= =" + key);//indicates that the current node has been traversed marks[i] = 1;//depth traversal, here is the node where the setting starts StringBuilder path = new StringBuilder (Points[i] + "");d FSW (graph, Points, marks, I, path); System.out.println (Path.tostring ());}}} Deep traverse public void dfsw (int graph[][], char points[], int marks[], int curindex, StringBuilder path) {//Traverse other nodes to determine if connected for (in t i = 0; i < marks.length; ++i) {//traversal sequence, and get the corresponding position indexint Curnum = graph[curindex][i];if (marks[i] = = 0 && curnum! = 0) {//This node has not been accessed, and this node Up to//system.out.println ("=" + points[i]);p ath.append ("= =" + Points[i]) marks[i] = 1;//recursion to the next DFSW (graph, points, Marks, I, Path);}}} @Testpublic void Test1 () {Dfs dfs = new DFS ();//a,b,c,d,e,f,g,h,i,j altogether 10 nodes, two trees//the following is a matrix diagram, 0 means not connected, 1 means connected, the node itself to itself 0int graph[][] = {//a,b,c,d,e,f,g,h,i,j{ 0,0,1,1,1,0,0,0,0,0},//a to other node {0,0,0,0,1,1,0,0,0,0},//b to other node {1,0,0,1,0,1,0,0,0,0},//c to other node {1,0,1,0,0,0,0,0,0,0} ,//d to other nodes {1,1,0,0,0,1,0,0,0,0},//e to other nodes {0,1,1,0,1,0,0,0,0,0},//f to other nodes {0,0,0,0,0,0,0,1,0,1},//g to other nodes { 0,0,0,0,0,0,1,0,1,0},//h to other nodes {0,0,0,0,0,0,0,1,0,1},//i to other nodes {0,0,0,0,0,0,1,0,1,0}//j to other nodes};char points[] = {' A ', ' B ' ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J '};int marks[] = {0,0,0,0,0,0,0,0,0,0};d fs.deepfirstsearch (graph, points, marks);} }
Results:
"Fundamentals of Algorithmic Design and analysis" 10, depth-first traversal