图的遍历——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

相关文章
相关标签/搜索