# 图的深度优先 VS 广度优先

由于前面讲解的点较少,恰好输出顺序一致,现在来对比下多一点的点。如下图

image-20210102151953031

 /**
     * 构建数量较多的点的 图
     *
     * @return
     */
    private Grap buildGrap2() {
        String vertexValue[] = {"1", "2", "3", "4", "5", "6", "7", "8"};
        Grap grap = new Grap(vertexValue.length);
        for (String value : vertexValue) {
            grap.insertVertex(value);
        }
        // a,b  a,c  b,c  b,d  b,e
        grap.insertEdge(0, 1, 1);
        grap.insertEdge(0, 2, 1);
        grap.insertEdge(1, 3, 1);
        grap.insertEdge(1, 4, 1);
        grap.insertEdge(3, 7, 1);
        grap.insertEdge(4, 7, 1);
        grap.insertEdge(2, 5, 1);
        grap.insertEdge(2, 6, 1);
        grap.insertEdge(5, 6, 1);
        return grap;
    }

    /**
     * 图的深度优先遍历:点数量较多的测试
     */
    @Test
    public void dfsTest2() {
        Grap grap = buildGrap2();
        grap.showGraph();

        System.out.println();
        grap.dfs();
    }

    /**
     * 图的广度优先遍历:点数量较多的测试
     */
    @Test
    public void bfsTest2() {
        Grap grap = buildGrap2();
        grap.showGraph();

        System.out.println();
        grap.bsf();
    }
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

测试输出:深度优先

  1 2 3 4 5 6 7 8 
1 0 1 1 0 0 0 0 0 
2 1 0 0 1 1 0 0 0 
3 1 0 0 0 0 1 1 0 
4 0 1 0 0 0 0 0 1 
5 0 1 0 0 0 0 0 1 
6 0 0 1 0 0 0 1 0 
7 0 0 1 0 0 1 0 0 
8 0 0 0 1 1 0 0 0 

1 -> 2 -> 4 -> 8 -> 5 -> 3 -> 6 -> 7 -> 
1
2
3
4
5
6
7
8
9
10
11

测试输出:广度优先

  1 2 3 4 5 6 7 8 
1 0 1 1 0 0 0 0 0 
2 1 0 0 1 1 0 0 0 
3 1 0 0 0 0 1 1 0 
4 0 1 0 0 0 0 0 1 
5 0 1 0 0 0 0 0 1 
6 0 0 1 0 0 0 1 0 
7 0 0 1 0 0 1 0 0 
8 0 0 0 1 1 0 0 0 

1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 
1
2
3
4
5
6
7
8
9
10
11