深度優先搜索
阿新 • • 發佈:2018-05-14
graph 沒有 class 鄰接 輸出結果 深度優先 img arch info
深度優先搜索用於尋找圖(G)中與頂點s連通的其它頂點。
設計一個類實現該算法,類的API如下:
算法實現
用遞歸的方法來遍歷所有的頂點,在訪問一個頂點時:
將它標記為已訪問;
遞歸的訪問它的沒有被標記的鄰接點。
實現代碼如下:
public class DepthFirstSearch { private boolean[] marked; private int count; /** * Find the vertices connected to vertex s */ public DepthFirstSearch(Graph G, ints) { marked = new boolean[G.V()]; dfs(G, s); } private void dfs(Graph G, int v) { marked[v] = true; count++; for (int w:G.adj(v)) if (!marked[w]) dfs(G, w); } /** * Is vertex v connected to s */ publicboolean marked(int v) { return marked[v]; } /** * Return the count of vertices connected to s */ public int count() { return count; } }
測試下圖,與頂點0連通的頂點
public static void main(String[] args) { Graph G = new Graph(13); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(0, 5); G.addEdge(0, 6); G.addEdge(3, 4); G.addEdge(3, 5); G.addEdge(4, 5); G.addEdge(4, 6); G.addEdge(7, 8); G.addEdge(9, 10); G.addEdge(9, 11); G.addEdge(9, 12); G.addEdge(11, 12); DepthFirstSearch search = new DepthFirstSearch(G, 0); for (int i=0; i<G.V(); i++) if (search.marked(i)) System.out.print(i + " "); }
輸出結果:0 1 2 3 4 5 6
深度優先搜索