图的DFS深度遍历

最近复习了一下图的内容,记录一下,后续添加详解(无向图的深度遍历)

package com.qey.learn;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @ClassName graph
 * @Description
 * @Author qianxl
 * @Date 2021-03-06 17:18
 * @Version 1.1
 **/
public class Graph {
    private int [][] edges;
    private ArrayList<String>  vertexList;
    private  int numOfEdges=0;
    private  boolean []isVisited;
    public Graph(int n){
        edges =new int[n][n];
        vertexList =new ArrayList<String>(n);
        isVisited=new boolean[n];
    }


    public static void main(String[] args) {
        Graph graph = new Graph(5);
        //初始化
        String[]  array={"A","B","C","D","E"};
        for(int i=0;i<array.length;i++){
           graph.vertexList.add(array[i]);
        }
        System.out.println(graph.vertexList.toString());
        // A-B A-C   B-C  B-D  B-E
        graph.inertEdges(0,1,1);
        graph.inertEdges(0,2,1);
        graph.inertEdges(1,2,1);
        graph.inertEdges(1,3,1);
        graph.inertEdges(1,4,1);
        graph.showGraph();


        graph.dfs();

    }

    public void inertEdges(int v1,int v2,int weigh){
        edges[v1][v2]=weigh;
        edges[v2][v1]=weigh;
        numOfEdges++;
    }

    public int getNumOfEdges() {
        return numOfEdges;
    }
    //获取顶点
    public String getVertex(int index){
        return vertexList.get(index);
    }
    //获取边
    public  int getEdges(int v1,int v2){
      return  edges[v1][v2];
    }
    //输出邻接矩阵
    public void showGraph(){
       for(int[] line:edges){
           System.out.println(Arrays.toString(line));
       }
    }

    //获取第一个邻接点
    public int getNeighbor(int index){
        for(int j=0;j<vertexList.size();j++){
            if(edges[index][j]>0){
                return  j;
            }
        }
        return  -1;
    }
    //获取当前邻接点的下一个邻接点
    public int getNeighbor(int v1,int v2){
        for(int j=v2+1;j<vertexList.size();j++){
            if(edges[v1][j]>0){
                return  j;
            }
        }
        return  -1;
    }

    /**
     *
     * [0, 1, 1, 0, 0]
     * [1, 0, 1, 1, 1]
     * [1, 1, 0, 0, 0]
     * [0, 1, 0, 0, 0]
     * [0, 1, 0, 0, 0]
     * @param v
     */
    //dfs 第一轮
    public  void  dfs(boolean [] isVisited,int v){

        System.out.print(getVertex(v)+"->");

        isVisited[v]=true;
        int w = getNeighbor(v);
        while(w!=-1){
            if(!isVisited[w]){
                dfs(isVisited,w);
            }
            w=getNeighbor(v,w);
        }

    }


    public void dfs(){
        for(int i=0;i<numOfEdges;i++){
            if(!isVisited[i]){
                dfs(isVisited,i);
            }

        }
    }





}

猜你喜欢

转载自blog.csdn.net/JHON07/article/details/114451820

相关文章