深度优先遍历(Depth First Search),从图中某个顶点V出发,访问此顶点,然后从v顶点的未被访问的邻接点出发,深度优先遍历图,直至图中所有和v有路径相通的顶点都被访问到。以下图为例
BFS示例
定义图的数据结构
pbulic class Graph {public String[] vertexs;public int[][] edageMatrix;public Graph(String[] vertexs) {this.vertexs = vertexs;this.edageMatrix = new int[vertexs.length][vertexs.length];}public void addEdage(int i, int j) {this.edageMatrix[i][j] = 1;}public int[] getAdjVertex(int i) {return this.edageMatrix[i];}}
使用深度优先遍历图的顶点,
public static void main(String[] args) {String[] vertexs = {"A0", "B1", "C2", "D3", "E4", "F5", "G6", "H7"};Set<Integer> visited = new LinkedHashSet<Integer>();Graph graph = new Graph(vertexs);graph.addEdage(0, 1);graph.addEdage(0, 5);graph.addEdage(1, 2);graph.addEdage(1, 6);graph.addEdage(2, 3);graph.addEdage(5, 6);graph.addEdage(5, 4);graph.addEdage(5, 7);graph.addEdage(6, 3);DFS(0, visited, graph);for (int i : visited) {System.out.print(vertexs[i] + "->");}}
DFS深度优先遍历
public static void DFS(int index, Set<Integer> visited, Graph graph) {if (visited.contains(index)) {return;}visited.add(index);int[] adj = graph.getAdjVertex(index);for (int i = 0; i < adj.length; i++) {if (adj[i] == 1) DFS(i, visited, graph);}}
