图的遍历

定义图的数据结构

邻接表的形式

public class Graph
{
    private final int numberOfNodes;
    private final LinkedList<Integer>[] adjacencyList;

    Graph(int nodesCount)
    {
        numberOfNodes = nodesCount;
        adjacencyList = new LinkedList[numberOfNodes];

        for(int i=0;i<numberOfNodes;i++)
        {
            adjacencyList[i] = new LinkedList();
        }
    }

    void addEdge(int a, int b)
    {
        adjacencyList[a].add(b);
        adjacencyList[b].add(a);
    }
}

广度优先遍历 BFS

利用辅助数组visited记录结点访问情况

注意需要考虑非连通图

public void BFS_traverse(){
        boolean[] visited = new boolean[numberOfNodes];
        for (int i = 0; i < numberOfNodes; ++i) {
            visited[i] = false;
        }
        for(int i=0;i<numberOfNodes;++i){
            if(!visited[i]){
                BFS(visited);
            }
        }
    }

    public void BFS(boolean[] visited) {
        LinkedList<Integer> queue = new LinkedList<>();
        System.out.println(0);
        visited[0] = true;
        queue.offer(0);
        while (!queue.isEmpty()) {
            int current = queue.poll();
            for (int tmp : adjacencyList[current])
                if (!visited[tmp]) {
                    System.out.println(tmp);
                    visited[tmp] = true;
                    queue.offer(tmp);
                }
        }
    }

深度优先遍历 DFS

public void DFS_traverse(){
        boolean[] visited = new boolean[numberOfNodes];
        for (int i = 0; i < numberOfNodes; ++i) {
            visited[i] = false;
        }
        for(int i=0;i<numberOfNodes;++i){
            if(!visited[i]){
                DFS(i,visited);
            }
        }
    }
    public void DFS(int vertex,boolean[] visited){
        System.out.println(vertex);
        visited[vertex]=true;
        for(int item:adjacencyList[vertex]){
            if(!visited[item]) {
                DFS(item,visited);
            }
        }
    }

邻接矩阵Adjacency Matrix存储形式的时间复杂度均为O(|V|2)

邻接表Adjacency List存储形式的时间复杂度均为O(|V|+|E|)

 

posted @ 2021-10-19 22:15  梦想家肾小球  阅读(30)  评论(0编辑  收藏  举报