圖的 深度優先搜尋(DFS) 以及 廣度優先搜尋(BFS)

來源:互聯網
上載者:User

1、深度優先

儘快遠離起始點

哭著鬧著找到最遠處的節點(所以,“深度優先” 可以理解為 “遠度優先”)

1. 先訪問起始點的 一個 鄰居

2. 以此 鄰居 為跳板,將 此鄰居 的所有鄰居都訪問完成(當然,在訪問  鄰居的鄰居  時候,  鄰居的鄰居的鄰居  也要都被訪問完成,最終的結果是 從此鄰居向後,其實統統被訪問過了)

3.   2  完成後,再回到起始點,然後訪問起始點的 下一個 鄰居

從這裡的 1, 2, 3 中可以很明顯的看出“遠離起始點,盡量訪問最遠處的節點”


2、廣度優先

水波紋擴充的過程(靠近自己的先都訪問完)
先訪問所有靠近自己的節點後,完成後才會再找外面一層

儘可能的靠近起始點


說實話,其實挺簡單的。

大學時之所以學的那麼苦,100% 還是因為當時沒有那怕一丁點的編程基礎。半點鐘編程經驗都沒有,還要看複雜的一毛的 C/C++ 代碼,也不知道偌大的教室裡面是不是有個同學真的理解了。可能也有NB的哥們理解了吧,反正以我的智商實在做不到啊。

還好,這次自己補補吧,權當是兒童讀物了,真的不算難

好了,把代碼 paste 上吧,權當給自己作個記錄,共四個檔案:

Vertex.java

/** * Describe the vertex in the graph *  */public class Vertex {private Object carryingInfo;private boolean wasVisited;public Object getCarryingInfo() {return carryingInfo;}public void setCarryingInfo(Object carryingInfo) {this.carryingInfo = carryingInfo;}public boolean isWasVisited() {return wasVisited;}public void setWasVisited(boolean wasVisited) {this.wasVisited = wasVisited;}public Vertex(Object carryingInfo) {this.carryingInfo = carryingInfo;wasVisited = false;}@Overridepublic String toString() {return carryingInfo.toString();}}


Graph.java

public class Graph {/** * The maximal permitted count of vertices. The real vertices count is * <code>nVerts</code> */public static final int MAX_VERTEX = 20;/** * Matrix used to store the relationship among vertices. *  * Some tailing rows and columns may be empty, the effective row/column * count <code>nVerts</code> */public int[][] adjMat = new int[MAX_VERTEX][MAX_VERTEX];/** * Array used to store each vertex *  * The effective counts of this array is <code>nVerts</code> */public Vertex[] arrayVertices = new Vertex[MAX_VERTEX];/** * Real vertices count */public int nVerts;public Graph() {nVerts = 0;for (int row = 0; row < MAX_VERTEX; row++) {for (int column = 0; column < MAX_VERTEX; column++) {adjMat[row][column] = 0;}}}public void addVertex(Object carryingInfo) {Vertex v = new Vertex(carryingInfo);arrayVertices[nVerts] = v;nVerts++;}public void addEdge(int start, int end) {adjMat[start][end] = 1;adjMat[end][start] = 1;}public void removeEdge(int start, int end) {adjMat[start][end] = 0;adjMat[end][start] = 0;}public void displayVertex(Vertex v) {System.out.println(v.getCarryingInfo());}}


SearchGraph.java

import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Stack;public class SearchGraph {public static List<Object> dfs(Graph g) {List<Object> listAccessOrder = new ArrayList<Object>();// elements in it had already been visitedStack<Vertex> stack = new Stack<Vertex>();Vertex startVertex = pickFirstAccessVertex(g);stack.push(startVertex);startVertex.setWasVisited(true);listAccessOrder.add(startVertex.getCarryingInfo());System.out.println("Push into stack: " + startVertex);while (!stack.empty()) {Vertex topVertex = stack.peek();// This had already been visited. We// peek it(not pop), and find one// unvisited neighbour of it(Some// neighbours had already been// visited, but the other had not.// So, we're going to find one of// the unvisited neighbours)// Find its next unvisted neighbourVertex unvisitedNeighbour = findOneUnVisitedNeighbour(g, topVertex);// Yes, we find a vertex of this kindif (unvisitedNeighbour != null) {stack.push(unvisitedNeighbour);// (Of course, this new pushed// one is the next peeked// vertex)unvisitedNeighbour.setWasVisited(true);listAccessOrder.add(unvisitedNeighbour.getCarryingInfo());System.out.println("Push into stack: " + unvisitedNeighbour);}// No, no this kind of neighbourelse {System.out.println("Stack status just before pop: " + stack);stack.pop();// topVertex(it's on the top of stack). When pop, we// cannot find any neighbours which had NOT been// visited(all neighbours of this vertex had already// been visited)}}return listAccessOrder;}public static List<Object> bfs(Graph g) {List<Object> listAccessOrder = new ArrayList<Object>();Queue<Vertex> queue = new LinkedList<Vertex>();Vertex startVertex = pickFirstAccessVertex(g);queue.offer(startVertex);startVertex.setWasVisited(true);listAccessOrder.add(startVertex.getCarryingInfo());System.out.println("Offer for Queue: " + startVertex);while (!queue.isEmpty()) {System.out.println("Queue status just before poll: " + queue);Vertex headVertex = queue.poll();// This had already been visited.// When poll a vertex, this// polled one had already been// visited, but NONE of its// neighbours// except that one who introduce// it into the queue has been// visitedList<Vertex> listAllRemainingUnvisitedNeighbour = findAllRemainingUnVisitedNeighbour(g, headVertex);// Yes, we find all remaining vertices of this kindif (listAllRemainingUnvisitedNeighbour.size() > 0) {for (Iterator<Vertex> it = listAllRemainingUnvisitedNeighbour.iterator(); it.hasNext();) {Vertex oneNeighbour = (Vertex) it.next();queue.offer(oneNeighbour);// When offer into queue, this one// had already been visited, but// its neighbours except// <code>headVertex</code> have// NOT been visited yetoneNeighbour.setWasVisited(true);listAccessOrder.add(oneNeighbour.getCarryingInfo());System.out.println("Offer for Queue: " + oneNeighbour);}}// No, no this kind of neighbourelse {}}return listAccessOrder;}private static Vertex pickFirstAccessVertex(Graph g) {return g.arrayVertices[0];}private static Vertex findOneUnVisitedNeighbour(Graph g, Vertex v) {int row = -1;for (int i = 0; i < g.nVerts; i++) {if (g.arrayVertices[i] == v) {row = i;break;}}if (row < 0) {return null;// never happen}for (int column = 0; column < g.nVerts; column++) {// not only neighbour of v, but also not been visitedif (g.adjMat[row][column] == 1&& g.arrayVertices[column].isWasVisited() == false) {return g.arrayVertices[column];}}return null;}private static List<Vertex> findAllRemainingUnVisitedNeighbour(Graph g,Vertex v) {List<Vertex> listAllUnvisitedNeighbour = new ArrayList<Vertex>();int row = -1;for (int i = 0; i < g.nVerts; i++) {if (g.arrayVertices[i] == v) {row = i;break;}}if (row < 0) {return listAllUnvisitedNeighbour;// never happen}for (int column = 0; column < g.nVerts; column++) {// not only neighbour of v, but also not been visitedif (g.adjMat[row][column] == 1&& g.arrayVertices[column].isWasVisited() == false) {listAllUnvisitedNeighbour.add(g.arrayVertices[column]);}}return listAllUnvisitedNeighbour;}}


Main.java

import java.util.List;public class Main {public static Graph createTestGraph() {Graph g = new Graph();g.addVertex("A");g.addVertex("B");g.addVertex("C");g.addVertex("D");g.addVertex("E");g.addVertex("F");g.addVertex("G");g.addVertex("H");g.addVertex("I");g.addEdge(0, 1);// A--Bg.addEdge(0, 2);// A--Cg.addEdge(0, 3);// A--Dg.addEdge(0, 4);// A--Eg.addEdge(1, 5);// B--Fg.addEdge(5, 7);// F--Hg.addEdge(3, 6);// D--Gg.addEdge(6, 8);// G--Ireturn g;}public static void main(String[] args) {System.out.println("Begin dfs search");List dfsAccessOrder = SearchGraph.dfs(createTestGraph());System.out.println("dfs: " + dfsAccessOrder);System.out.println("Begin bfs search");List bsfAccessOrder = SearchGraph.bfs(createTestGraph());System.out.println("bfs: " + bsfAccessOrder);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.