[Basis of algorithm design and analysis] 10. depth-first traversal, algorithm design and analysis depth
Package cn. xf. algorithm. ch03; import org. junit. test;/*** depth-first traversal * @ author xiaof **/public class DFS {public void deepFirstSearch (int graph [] [], char points [], int marks []) {// all points of the bar are set to 0, indicating that the for (int I = 0; I <marks. length; ++ I) {marks [I] = 0;} // traverse all nodes and access for (int I = 0; I <points. length; ++ I) {// judge if (marks [I] = 0) this node has not been accessed {// System. out. println ("=>" + key); // indicates that the current node has been traversed by marks [I] = 1; // depth traversal. Here is Set the Start Node StringBuilder path = new StringBuilder (points [I] + ""); dfsw (graph, points, marks, I, path); System. out. println (path. toString () ;}}// traverse public void dfsw in depth (int graph [] [], char points [], int marks [], int curIndex, StringBuilder path) {// traverse other nodes to determine if they are connected for (int I = 0; I <marks. length; ++ I) {// traverse the sequence and obtain the corresponding position indexint curNum = graph [curIndex] [I]; if (marks [I] = 0 & curNum! = 0) {// This node has not been accessed yet, and this node can be reached // System. out. println ("=>" + points [I]); path. 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 has a total of 10 nodes, two trees // The following is a matrix chart, 0 indicates not connected, 1 indicates connected, the Node itself is 0int graph [] [] = {// a, B, c, d, e, f, g, h, I, j, ,}, // a to another node {0, 0,}, // B to another node {, 0, 0, 0, 0}, // c to other nodes {, 0,}, // d to other nodes {, 0, 0, 0, 0 }, // e to other nodes {0, 1, 0, 1, 0, 0, 0, 0}, // f to other nodes {0, 0, 0, 0, 0, 0, 0, 1, 0 }, // g to other nodes {0, 0, 0, 0, 0, 1, 0}, // h to other nodes {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, // I to other nodes {0, 0, 0, 0, 0, 1, 0} // j to another node}; char points [] = {'A', 'B ', 'C', 'D', 'E', 'F', 'G', 'h', 'I', 'J '}; int marks [] = {0, 0, 0, 0, 0, 0, 0}; dfs. deepFirstSearch (graph, points, marks );}}
Result: