• 数据结构Java版之深度优先-图(十二)


    这里用深度优先遍历存在矩阵里面的图。

      深度优先利用的是栈的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 + " "); } //获得邻接未访问节点 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();
        }

    测试结果:

    10001
    00001
    10001
    01110
    A    B    E    C    D
  • 相关阅读:
    DBSCAN密度聚类
    特征工程之特征预处理
    特征工程之特征表达
    特征工程之特征选择
    Adaboost,GBDT和XGboost算法
    036 Go操作NSQ
    035 Go操作Redis
    034 Go操作MySQL
    033 protobuf初识
    032 二进制协议gob及msgpack介绍
  • 原文地址:https://www.cnblogs.com/ranter/p/9250017.html
Copyright © 2020-2023  润新知