圖的生成樹

圖模型

無向圖

圖的生成樹

public class TestA {

    public static void main(String[] args) {

        TestA a = new TestA();
        a.bfs(2);

    }

    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" };

    int[] book = new int[5];

    private class Node {

        int x;
        Node preNode;
        int step;

        public Node(int x, int step, Node preNode) {
            this.x = x;
            this.step = step;
            this.preNode = preNode;
        }

    }

    Stack<Node> stack = new Stack<>();

    void bfs(int start) {

        Node node = new Node(start, 1, null);
        stack.push(node);
        while (!stack.isEmpty()) {
            Node newNode = stack.pop();

            book[newNode.x] = 1;

            print(newNode);
            System.out.println();

            for (int i = edge.length - 1; i >= 0; i--) {

                if (edge[newNode.x][i] > 0 && book[i] == 0) {

                    stack.push(new Node(i, newNode.step + 1, newNode));

                }
            }
        }
    }

    public void print(Node node) {
        if (node == null) {
            return;
        }
        print(node.preNode);
        System.out.print("--->" + vertex[node.x]);

    }
}

輸出結果

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