欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图的深度优先遍历与广度优先遍历

程序员文章站 2022-03-03 11:34:12
...
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class GraphTest1 {
    public static void main(String[] args) {
        Graph1 graph = new Graph1(9);
        graph.insertVertex("A");
        graph.insertVertex("B");
        graph.insertVertex("C");
        graph.insertVertex("D");
        graph.insertVertex("E");
        graph.insertVertex("F");
        graph.insertVertex("G");
        graph.insertVertex("H");
        graph.insertVertex("I");
        graph.insertEdge(0, 1);
        graph.insertEdge(0, 3);
        graph.insertEdge(0, 4);
        graph.insertEdge(1, 2);
        graph.insertEdge(1, 3);
        graph.insertEdge(2, 5);
        graph.insertEdge(6, 7);
        graph.insertEdge(6, 4);
        graph.insertEdge(7, 8);
        graph.insertEdge(3, 6);
        //graph.dfs(0);
        graph.bfs(0);
    }
}

class Graph1 {
    ArrayList<String> vertexList;//存储结点的集合
    int[][] edges;//存储邻接矩阵
    boolean[] isVisted;//false表示该结点未被访问

    public Graph1(int n) {
        edges = new int[n][n];
        isVisted = new boolean[n];
        vertexList = new ArrayList<>(n);
    }

    public void insertVertex(String vertex) {
        vertexList.add(vertex);
    }

    public void insertEdge(int x, int y) {
        edges[x][y] = 1;
        edges[y][x] = 1;
    }

    public String getVertex(int i) {
        return vertexList.get(i);
    }

    public void dfs(int i) {
        System.out.print(getVertex(i) + "  ");
        isVisted[i] = true;
        for (int j = 0; j < edges.length; j++) {
            if (!isVisted[j] && edges[i][j] == 1) {
                dfs(j);
            }
        }
    }

    public void bfs(int i) {
        Queue<Integer> queue = new LinkedList<>();
        System.out.print(getVertex(i) + "  ");
        isVisted[i] = true;
        queue.add(i);
        while (!queue.isEmpty()) {
            int j = queue.poll();
            for (int k = 0; k < edges.length; k++) {
                if (!isVisted[k] && edges[j][k] == 1) {
                    queue.add(k);
                    System.out.print(getVertex(k) + "  ");
                    isVisted[k] = true;
                }
            }
        }
    }
}
相关标签: dfs bfs 队列