圖的遍歷——DFS

原創java


圖的遍歷有DFS和BFS兩種,現選用DFS遍歷圖。spa

存儲圖用鄰接矩陣,圖有v個頂點,e條邊,鄰接矩陣就是一個VxV的矩陣;code

若頂點1和頂點5之間有連線,則矩陣元素[1,5]置1,如果無向圖[5,1]也blog

置1,兩頂點之間無連線則置無窮,頂點到頂點自己置0。class

例如:import

鄰接矩陣爲:bfc

遍歷思路:遍歷

  隨便選擇一未訪問過的頂點v1做爲遍歷起點,訪問v1,再選擇與v1鏈接的點v2做爲起始點,訪問v2;im

再選擇與v2鏈接的點做爲起始點v3,訪問v3,假設v3是孤立點,則v3不能往下訪問,回溯到v2,再以v2d3

做爲起點,訪問與v2鏈接的其餘未被訪問過的頂點,假設是v4,則再以v4爲頂點,訪問v4,再選擇與v4

鏈接的頂點爲起始點......直到所有頂點都被訪問過一遍。

  在上圖中,假設以頂點2爲起點進行圖的遍歷,則先訪問頂點2,再訪問頂點1,注意,並非先訪問

3,由於在掃描鄰接矩陣時,在每行是從左向右掃描的;再訪問頂點0,再深搜下去訪問頂點4,訪問頂點

5,一直回溯,回溯到頂點2,再訪問頂點3;訪問順序爲:2 1 0 4 5 3 

Java:

import java.util.*;

public class 圖的遍歷_dfs {
    
    static int v;    //頂點數
    static int e;    //邊數
    static int arr[][];
    static int book[];    //標識頂點是否訪問
    static int max=99999;    //無窮
    static int total=0;    //統計已訪問頂點個數
    
    static void graph_dfs(int ver) {    //ver表示頂點
        total++;
        book[ver]=1;    //標記頂點ver已經訪問過
        System.out.print(ver+" ");
        if(total==v) {
            return;
        }
        for(int i=0;i<v;i++) {
            if(arr[ver][i]==1 && book[i]==0) {
                graph_dfs(i);
            }
        }
        return;
    }

    public static void main(String[] args) {
        Scanner reader=new Scanner(System.in);
        v=reader.nextInt();
        e=reader.nextInt();
        arr=new int[v][v];
        book=new int[v];
        //鄰接矩陣初始化
        for(int i=0;i<v;i++) {
            book[i]=0;
            for(int j=0;j<v;j++) {
                if(i==j) {
                    arr[i][j]=0;
                }
                else {
                    arr[i][j]=max;
                }
            }
        }
        //讀入邊
        for(int i=0;i<e;i++) {
            int first_E=reader.nextInt();
            int second_E=reader.nextInt();
            arr[first_E][second_E]=1;
            arr[second_E][first_E]=1;
        }
        graph_dfs(0);    //從頂點0開始遍歷
    }

}

18:08:52

2018-07-22

相關文章
相關標籤/搜索