深度优先遍历(Depth First Search),从图中某个顶点V出发,访问此顶点,然后从v顶点的未被访问的邻接点出发,深度优先遍历图,直至图中所有和v有路径相通的顶点都被访问到。以下图为例

图的深度优先遍历 - 图1

BFS示例

定义图的数据结构

  1. pbulic class Graph {
  2. public String[] vertexs;
  3. public int[][] edageMatrix;
  4. public Graph(String[] vertexs) {
  5. this.vertexs = vertexs;
  6. this.edageMatrix = new int[vertexs.length][vertexs.length];
  7. }
  8. public void addEdage(int i, int j) {
  9. this.edageMatrix[i][j] = 1;
  10. }
  11. public int[] getAdjVertex(int i) {
  12. return this.edageMatrix[i];
  13. }
  14. }

使用深度优先遍历图的顶点,

  1. public static void main(String[] args) {
  2. String[] vertexs = {"A0", "B1", "C2", "D3", "E4", "F5", "G6", "H7"};
  3. Set<Integer> visited = new LinkedHashSet<Integer>();
  4. Graph graph = new Graph(vertexs);
  5. graph.addEdage(0, 1);
  6. graph.addEdage(0, 5);
  7. graph.addEdage(1, 2);
  8. graph.addEdage(1, 6);
  9. graph.addEdage(2, 3);
  10. graph.addEdage(5, 6);
  11. graph.addEdage(5, 4);
  12. graph.addEdage(5, 7);
  13. graph.addEdage(6, 3);
  14. DFS(0, visited, graph);
  15. for (int i : visited) {
  16. System.out.print(vertexs[i] + "->");
  17. }
  18. }

DFS深度优先遍历

  1. public static void DFS(int index, Set<Integer> visited, Graph graph) {
  2. if (visited.contains(index)) {
  3. return;
  4. }
  5. visited.add(index);
  6. int[] adj = graph.getAdjVertex(index);
  7. for (int i = 0; i < adj.length; i++) {
  8. if (adj[i] == 1) DFS(i, visited, graph);
  9. }
  10. }