无向图的深度优先搜索(非递归)(Java)

一、问题

找到一条1到6的路径

       1  -  2  -  3
       丨    丨    丨
       4  -  5  -  6

 

二、代码

Java

import java.util.Deque;
import java.util.LinkedList;

public class UndirectedLinkedGraph {
    private int vertexNum;             // 顶点个数
    private LinkedList<Integer> adj[]; // 邻接表

    public UndirectedLinkedGraph(int vertexNum) {
        this.vertexNum = vertexNum;

        adj = new LinkedList[vertexNum];
        for (int i = 0; i < vertexNum; ++i) {
            adj[i] = new LinkedList<>();
        }
    }

    public void addEdge(int from, int to) { // 无向图一条边存两次
        adj[from].add(to);
        adj[to].add(from);
    }

    /**
     * 创建
     *
     * 1  -  2  -  3
     * 丨    丨    丨
     * 4  -  5  -  6
     */
    public void build() {
        addEdge(1, 2);
        addEdge(1, 4);

        addEdge(2, 3);
        addEdge(2, 5);

        addEdge(3, 6);
        addEdge(4, 5);
        addEdge(5, 6);
    }

    public void printProcess(Integer[] process, Integer index) {
        if (index >= 0) {
            printProcess(process, process[index]);
            System.out.print(index + "    ");
        }
    }



    /**
     * 深度优先搜索 (借助栈)
     */
    public void dfs(int start, int target) {
        if (start == target) {
            return;
        }

        //节点是否访问过了
        Boolean[] hasEnHeap = new Boolean[vertexNum];
        for (int i = 1; i < vertexNum; i++) {
            hasEnHeap[i] = false;
        }

        //遍历的辅助队列
        Deque<Integer> heap = new LinkedList<>();
        heap.offer(start);
        hasEnHeap[start] = true;

        //遍历的过程(存上一个节点的index)
        Integer[] process = new Integer[vertexNum];
        for(int i=0; i<process.length; i++) {
            process[i] = -1;
        }

        while (!heap.isEmpty()) {
            //栈顶出栈
            Integer top = heap.pollLast();

            //top能到达的点入队
            for (Integer topCanReceive : adj[top]) {
                if (topCanReceive == target) {
                    process[topCanReceive] = top;
                    printProcess(process, topCanReceive);
                    return;
                }
                if (!hasEnHeap[topCanReceive]) {  //节点出栈时,把跟节点连接的所有节点都入栈(已经入过栈的就不入栈了)
                    heap.offerLast(topCanReceive);
                    hasEnHeap[topCanReceive] = true;
                    process[topCanReceive] = top;
                }
            }
        }
    }

    public static void main(String[] args) {
        UndirectedLinkedGraph graph = new UndirectedLinkedGraph(7);  // 比实际顶点数+1
        graph.build();
        graph.dfs(1, 6);
    }
}

运行结果

1    4    5    6    
 

三、扩展

类似的:

     树的前序遍历 (非递归) (Java)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值