Java用邻接矩阵实现图并进行深度优先搜索

先定义节点类

class Vertex{
    char label;
    boolean wasVisited;
    public Vertex(char label){
        this.label = label;
        wasVisited = false; 
    }
}

图:

class Graph{
    private final int MAX_VERTS = 20;
    private Vertex vertexList[];//节点列表
    private int adjMat[][];//邻接矩阵
    private int nVerts;//节点数
    private Stack theStack;//协助栈

    public Graph(){
        vertexList = new Vertex[MAX_VERTS];
        adjMat = new int[MAX_VERTS][MAX_VERTS];
        nVerts = 0;
        for(int i = 0; i < MAX_VERTS; i++){
            for(int j = 0; j < MAX_VERTS; j++)
                adjMat[i][j] = 0;
        }

        theStack = new Stack();
    }

    public void addVertex(char lab){
        vertexList[nVerts++] = new Vertex(lab);
    }

    public void addEdge(int start, int end){
        adjMat[start][end] = 1;
        adjMat[end][start] = 1;
    }

    public void displayVertex(int v){
        System.out.print(vertexList[v].label);
    }

    //深度优先搜索
    /**
     * 深度优先搜索要得到距离起始点最远的顶点,然后不能继续前进的时候返回
     * 
     * 规则1:如果可能,访问一个邻接的未访问顶点,标记它,并把它放入栈中
     * 
     * 规则2:当不能执行规则1时,如果栈不空,就从栈中弹出一个顶点
     * 
     * 规则3:如果不能执行规则1和规则2,就完成了整个搜索过程
     */
    public void dfs(){
        vertexList[0].wasVisited = true;//从第一个节点开始,标记为已访问
        displayVertex(0);//打印
        theStack.push(0);//入栈

        while( !theStack.isEmpty()){
            //得到一个未被访问的邻接节点
            int v = getAdjUnvisiedVertex((int) theStack.peek());
            if(v == -1)//没有这样的节点,该点访问完成
                theStack.pop();
            else{//继续访问
                vertexList[v].wasVisited = true;
                displayVertex(v);
                theStack.push(v);
            }
        }
        //所有节点访问完毕,重置所有节点为为访问状态
        for(int j = 0; j < nVerts; j++){
            vertexList[j].wasVisited = false;
        }
    }

    //获取为v节点邻接的未被访问的节点
    public int getAdjUnvisiedVertex(int v){
        for(int i = 0; i < nVerts; i++){
            if(adjMat[v][i] == 1 && vertexList[i].wasVisited == false){
                return i;
            }
        }
        return -1;
    }
}

测试:

        Graph theGraph = new Graph();
        theGraph.addVertex('A');
        theGraph.addVertex('B');
        theGraph.addVertex('C');
        theGraph.addVertex('D');
        theGraph.addVertex('E');
        theGraph.addEdge(0, 1);
        theGraph.addEdge(1, 2);
        theGraph.addEdge(0, 3);
        theGraph.addEdge(3, 4);

        theGraph.dfs();

这里写图片描述
按深度优先搜索:
ABCDE

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值