深度優先遍曆步驟:
(1),訪問一個鄰接的未訪問頂點,標記它,並且把它放入棧中。
(2),當不能執行規則1時,如果棧不為空白,從棧中彈出一個頂點,重複執行規則1。
(3),如果規則1和規則2都不能執行時整個搜尋結束。
廣度優先遍曆步驟:
(1)、訪問一個未來訪問的鄰接點(如果存在),這個鄰接點必須是當前頂點的鄰接點,標記它,並且把它插入到隊列中。
(2)、如果不能執行規則1,那麼從隊列頭取一個頂點(如果存在),並事它成為當前頂點
(3)、如果不能執行規則1和規則2,則搜尋結束。
Graph_adjMat.java
package com.mapbar.structure;import java.util.LinkedList;import java.util.Stack;import java.util.Queue;/** * * Class Graph_adjMat.java * * Description * * Company mapbar * * author Chenll E-mail: Chenll@mapbar.com * * Version 1.0 * * Date 2011-11-16 下午03:38:27 *///定義節點class Vertex{public char label;public boolean isVisited;public Vertex(char label){this.label = label;this.isVisited = false;}}//public class Graph_adjMat {//頂點數組private Vertex[] vArr;//定義鄰接矩陣private int[][] adjMat; //頂點的最大數目 private int maxSize; //當前頂點 下標 private int currVertex; //構造方法 public Graph_adjMat(int maxSize){ this.maxSize = maxSize; vArr = new Vertex[maxSize]; adjMat = new int[maxSize][maxSize]; for (int i = 0; i<adjMat.length; i++){ for(int j = 0; j<adjMat.length; j++){ adjMat[i][j] = 0; } } currVertex = 0; } //添加一個頂點 public void addVertex(char label){ vArr[currVertex++] = new Vertex(label); } //添加一個邊 public void addEdge(int start,int end){ adjMat[start][end] = 1; adjMat[end][start] = 1; } //顯示一個定點 public void disVertex(int v){ System.out.print(vArr[v].label+","); } //深度遍曆 public void dfs(){ Stack<Integer> stack = new Stack<Integer>(); //開始訪問第一個頂點 vArr[0].isVisited = true; disVertex(0); //入棧 stack.push(0); while(!stack.isEmpty()){ int v = getUnvisitedVertex(stack.peek()); if(v==-1){ stack.pop(); } else { vArr[v].isVisited = true; disVertex(v); stack.push(v); } } reset(); } //廣度遍曆 public void bfs(){ //注意LinkedList類實現了Queue介面,因此我們可以把LinkedList當成Queue來用 Queue<Integer> queue = new LinkedList<Integer>(); vArr[0].isVisited = true; disVertex(0); queue.add(0); int v2; while(!queue.isEmpty()){ int v1 = queue.remove(); while((v2=getUnvisitedVertex(v1))!=-1){ vArr[v2].isVisited = true; disVertex(v2); queue.add(v2); } } reset(); } //尋找沒有訪問過的鄰接點 public int getUnvisitedVertex(int x){ for(int j = 0; j<currVertex; j++){ if(adjMat[x][j]==1 && vArr[j].isVisited ==false){ return j; } } return -1; } //頂點都置為false public void reset(){ for(int i = 0; i<currVertex; i++){ vArr[i].isVisited = false; } } //主調函數 public static void main(String[] args){ Graph_adjMat g = new Graph_adjMat(10); g.addVertex('a'); g.addVertex('b'); g.addVertex('c'); g.addVertex('d'); g.addVertex('e'); g.addVertex('f'); g.addEdge(0,1); g.addEdge(0,2); g.addEdge(1,3); System.out.println("深度優先遍曆:"); g.dfs(); System.out.println("\r\n廣度優先遍曆:"); g.bfs(); }}
output:
深度優先遍曆:
a,b,d,c,
廣度優先遍曆:
a,b,c,d,