其他分享
首页 > 其他分享> > 面试题 04.01. 节点间通路-----DFS、BFS

面试题 04.01. 节点间通路-----DFS、BFS

作者:互联网

题目表述

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

示例:

输入: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2

输出: true

DFS、BFS

bfs

class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        List<List<Integer>> graphlist = new ArrayList<>();
        for(int i= 0; i < n;i++){
            graphlist.add(new ArrayList<>());
        }
        for(int[] tmp : graph){
                graphlist.get(tmp[0]).add(tmp[1]);     
        }
        boolean[] visited = new boolean[n];
        return bfs(graphlist,start,target,visited);
    }
    public boolean bfs(List<List<Integer>> graph, int start, int target, boolean[] visited){
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        visited[start] = true;
        while (!queue.isEmpty()){
            int tmp = queue.poll();
            if(tmp == target){
                return true;
            }
            for(int i : graph.get(tmp)){
                if(visited[i]) continue;
                queue.offer(i);
                visited[i] = true;
            }
            
        }
        return false;
    }
}

dfs

class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        List<List<Integer>> graphlist = new ArrayList<>();
        for(int i= 0; i < n;i++){
            graphlist.add(new ArrayList<>());
        }
        for(int[] tmp : graph){
                graphlist.get(tmp[0]).add(tmp[1]);     
        }
        boolean[] visited = new boolean[n];
        return dfs(graphlist,start,target,visited);
    }
    public boolean dfs(List<List<Integer>> graph, int start, int target, boolean[] visited){
        visited[start] = true;
        if(start == target){
            return true;
        }
        for(int i : graph.get(start)){
            if(visited[i]) continue;
            if (dfs(graph,i,target,visited)) return true;
        }
        return false;
    }
}

标签:面试题,target,int,graph,DFS,BFS,start,boolean,visited
来源: https://www.cnblogs.com/youngerwb/p/16244507.html