資料結構Java版之深度優先-圖(十二)

來源:互聯網
上載者:User

標籤:matrix   rgs   AC   特性   結果   一個   star   svi   main   

這裡用深度優先遍曆存在矩陣裡面的圖。

  深度優先利用的是棧的FIFO特性。為此遍曆到底後,可以找到最相鄰的節點繼續遍曆。實現深度優先,還需要在節點加上一個訪問標識,來確定該節點是否已經被訪問過了。

源碼:

package mygraph;import java.util.Stack;public class DFS_Vertex {
   //建立一個我們需要的節點類 class Vertex { private char lable; private int val; private boolean wasvisited; Vertex(char lable) { this.lable = lable; } Vertex() { } } private char lable; // 矩陣元素 private Vertex[][] list = new Vertex[20][20]; private Vertex[] vertexList = new Vertex[20]; private int nVerts; // 當前頂點下標 DFS_Vertex() { this.nVerts = 0; for(int i = 0; i < 20; i ++) { for(int j = 0; j < 20; j ++) { list[i][j] = new Vertex(); } } } // 增加一個頂點 public void addVertex(char lable) { vertexList[nVerts++] = new Vertex(lable); } // 增加一條邊 public void addEdge(int start, int end) { list[start][end].val = 1; list[end][start].val = 1; } // 列印矩陣 public void printMatrix() { for (int i = 0; i < nVerts; i++) { for (int j = 0; j < nVerts; j++) { System.out.print(list[i][j].val); } System.out.println(); } } //顯示字元 public void showVertex(int v) { System.out.print(vertexList[v].lable + "\t"); } //獲得鄰接未訪問節點 public int getAdjUnvisitedVertex(int v) { for(int j = 0; j < nVerts; j ++) { if((list[v][j].val == 1) && (vertexList[j].wasvisited == false)) { return j; } } return -1; } //DFS public void DFS() { Stack<Integer> s = new Stack(); vertexList[0].wasvisited = true; showVertex(0); s.push(0); int v; while(s.size() > 0) { v = getAdjUnvisitedVertex(s.peek()); if(v == -1) { s.pop(); }else { vertexList[v].wasvisited = true; showVertex(v); s.push(v); } } for(int j = 0; j < nVerts; j ++) { vertexList[j].wasvisited = false; } }}

測試程式:

    public static void main(String[] args) {        DFS_Vertex ds = new DFS_Vertex();        ds.addVertex(‘A‘);    //0        ds.addVertex(‘B‘);    //1        ds.addVertex(‘C‘);    //2            ds.addVertex(‘D‘);    //3        ds.addVertex(‘E‘);    //4        ds.addEdge(0, 1);    //A-B         ds.addEdge(0, 3);    //A-D        ds.addEdge(1, 4);    //B-E        ds.addEdge(3, 4);    //D-E        ds.addEdge(4, 2);    //E-C        ds.printMatrix();        ds.DFS();    }

測試結果:

10001000011000101110A    B    E    C    D

 

資料結構Java版之深度優先-圖(十二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.