【leetcode】面试题 04.01. 节点间通路

节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。

示例1:

输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出:true
示例2:

输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
输出 true
提示:

节点数量n在[0, 1e5]范围内。
节点编号大于等于 0 小于 n。
图中可能存在自环和平行边。

题解:

class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        if(start < 0 || target >= n){
            return false;
        }

        // 首先获得邻接矩阵
        List<Integer>[] map = new LinkedList[n];
        for(int i = 0; i< graph.length; i++){
            int from = graph[i][0];
            int to = graph[i][1];
            if(map[from] == null){
                map[from] = new LinkedList<>();
            }
            map[from].add(to);
        }

        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];
        queue.offer(start);
        visited[start] = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            // 访问队列中的节点
            for(int i= 0; i< size; i++){
                int from = queue.poll();
                // 首先找到该节点后面的顶点列表
                List<Integer> list = map[from];
                // 如果该节点出度为0,则循环后面的
                if(list == null){
                    continue;
                }
                // 遍历列表
                for(Integer end : list){
                    int e = end;
                    // 如果列表中的节点有等于target的直接返回
                    if(e == target){
                        return true;
                    }
                    //  如果是之前访问过的节点,继续下一个节点
                    if(visited[e]){
                        continue;
                    }
                    // 设置当前节点为访问过的
                    visited[e] = true;
                    queue.offer(e);
                }
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值