跳至主要內容

图的深度优先遍历


图的深度优先遍历

介绍

深度优先遍历(Depth-First Search,DFS)是一种用于遍历或搜索树或图的算法。在深度优先遍历中,我们从某个顶点开始遍历图,当遇到一个未被访问过的相邻顶点时,就将其标记为已访问,并递归地访问该顶点的相邻顶点,直到所有相邻顶点都被访问过或者当前顶点没有未访问的相邻顶点为止。

深度优先遍历通常使用递归或栈来实现。具体来说,我们可以从图中的任意一个顶点开始,将其标记为已访问,并将其加入栈中。然后,我们从栈中弹出一个顶点,访问它的所有未被访问过的相邻顶点,并将这些相邻顶点标记为已访问,并依次将它们加入栈中。重复这个过程,直到栈为空,即遍历过程结束。

深度优先遍历对于处理连通图和处理树结构非常有用。它可以帮助我们找出图的连通分量、判断图是否为二分图、求解拓扑排序等问题。另外,深度优先遍历还可以用于解决迷宫问题、数独问题等。但需要注意的是,深度优先遍历的时间复杂度可能会达到O(n+m),其中n和m分别是图的顶点数和边数,因此在处理大规模图时,可能需要考虑使用其他的算法。

Java代码实现

public class DFS {
    public static String dfs(Graph g){
        String result = "";
        if (g.vertices < 1){
            return result;
        }
        boolean[] visited = new boolean[g.vertices];
        for(int i=0; i<g.vertices; i++) { 
            if(!visited[i]) { 
                result = result + dfsVisit(g, i, visited); 
            } 
        }
        return result;
    }
    public static String dfsVisit(Graph g, int source, boolean[] visited) {
        String result = "";
        Stack<Integer> stack = new Stack<Integer>(g.vertices);
        stack.push(source);
        while (!stack.isEmpty()) {
            int current_node = stack.pop();
            result += String.valueOf(current_node);
            DoublyLinkedList<Integer>.Node temp = null;
            if(g.adjacencyList[current_node] !=null)
                temp = g.adjacencyList[current_node].headNode;
            while (temp != null) {
                if (!visited[temp.data]) {
                    stack.push(temp.data);
                }
                temp = temp.nextNode;
            }
            visited[current_node] = true;
        }
        return result;
    }
}
上次编辑于:
贡献者: Neil