無向圖的深度優先搜索和廣度優先搜索

無向圖模型

無向圖

無向圖的深度優先搜索和廣度優先搜索

public class TestA {

    public static void main(String[] args) {

        TestA a = new TestA();
        a.dfs(0);
        a.bfs(1);

    }

    int[][] edge = { { 0, 1, 1, -1, -1 }, { 1, 0, -1, 1, 1 }, { 1, -1, 0, -1, 1 }, { -1, 1, -1, 0, -1 },
            { -1, 1, 1, -1, 0 } };
    String[] vertex = { "A", "B", "C", "D", "E" };

    Stack<Integer> stack = new Stack<>();
    int[] book = new int[5];

    void dfs(int cur) {

        book[cur] = 1;
        System.out.println("--- " + vertex[cur] + " ---");

        for (int i = 0; i < edge.length; i++) {
            if (edge[cur][i] == 1 && book[i] == 0) {
                dfs(i);
            }
        }
    }

    void bfs(int start) {

        System.out.println("#######");
        book = new int[5];
        stack.push(start);
        while (!stack.isEmpty()) {
            int cur = stack.pop();//從top[隊尾]取出數據並刪除
            book[cur] = 1;

            System.out.println("--- " + vertex[cur] + " ---");
            for (int i = 0; i < edge.length; i++) {

                if (edge[cur][i] == 1 && book[i] == 0) {
                    stack.push(i);//向top[隊尾]追加數據
                }
            }
        }
    }
}

輸出結果

--- A ---
--- B ---
--- D ---
--- E ---
--- C ---
#######
--- B ---
--- E ---
--- C ---
--- A ---
--- D ---
--- A ---
相關文章
相關標籤/搜索