1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
public class DFS {
private static int[] markArray;
private static int[] previousVertex;
public static void DFSDemo() {
Undigraph undigraph = getUndigraph(); Integer vertexNum = undigraph.getVertexNum(); markArray = new int[vertexNum]; previousVertex = new int[vertexNum];
Integer start = 0;
Boolean status = DFS(undigraph, start); if( status ) { visualPath(start, previousVertex); } }
private static Boolean DFS( Undigraph undigraph, Integer vertex) { markArray[vertex] = 1;
if( !undigraph.getAdjacencyList().containsKey(vertex) ) { return false; }
List<Integer> adjacencyList = undigraph.getAdjacencyList().get(vertex); for( Integer adjacencyVertex : adjacencyList ) { if( markArray[adjacencyVertex] != 1 ) { previousVertex[adjacencyVertex] = vertex; DFS(undigraph, adjacencyVertex); } } return true; }
private static void visualPath(Integer start, int[] resultPath) { for( int i=0; i<resultPath.length; i++ ) { List<String> path = new LinkedList<String>(); Integer vertex = i; while (vertex != start) { path.add( vertex.toString() ); vertex = resultPath[vertex]; } path.add(vertex.toString()); Collections.reverse(path); String pathStr = path.stream().collect( Collectors.joining("->") ); System.out.println(pathStr); } }
private static Undigraph getUndigraph() { Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
adjacencyList.put(0, Arrays.asList(2, 1, 5) ); adjacencyList.put(1, Arrays.asList(0, 2) ); adjacencyList.put(2, Arrays.asList(0, 1, 3, 4) ); adjacencyList.put(3, Arrays.asList(5, 4, 2) ); adjacencyList.put(4, Arrays.asList(2, 3) ); adjacencyList.put(5, Arrays.asList(3, 0) );
Undigraph undigraph = new Undigraph(); undigraph.setAdjacencyList( adjacencyList ); undigraph.setVertexNum( adjacencyList.size() ); return undigraph; } }
|