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

题目:

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

示例1:

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

 

解答:

方法一:由给出的graph数组构造邻接矩阵(超出内存范围)

class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        int[][] g = new int[n][n];
        for(int i  = 0;i<graph.length;i++){
            g[graph[i][0]][graph[i][1]] = 1;
        }

        LinkedList<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];
        queue.addLast(start);
        visited[start] = true;

        while(!queue.isEmpty()){
            int node = queue.removeFirst();
            if(node == target){
                return true;
            }
            for(int j = 0;j<n;j++){
                if(g[node][j]!=0){
                    queue.addLast(j);
                }
            }
        }


        return false;
    }
}

方法二:(超时)

class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        
        
        LinkedList<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];
        queue.addLast(start);
        visited[start] = true;
        int len = graph.length;

        while(!queue.isEmpty()){
            int node = queue.removeFirst();

            for(int j = 0;j<len;j++){
                if(graph[j][0] == node&&graph[j][1] == target){
                    return true;
                }else if(graph[j][0] == node&&!visited[graph[j][1]]){
                    queue.addLast(graph[j][1]);
                }
            }
        }


        return false;
    }
}

 

方法三:

由给定graph数组构造邻接表+BFS 

 

要注意的细节:

邻接表中可能存在以某个节点为根的链表不存在任何节点,即存在节点的出度为0的情况,要单独考虑
 
class Solution {
    public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
        
        //创建邻接表
        List<Integer>[] g = new ArrayList[n];
        int len = graph.length;
        for(int i = 0;i<len;i++){
            int x = graph[i][0];
            int y = graph[i][1];
            if(g[x] == null){
                g[x] = new ArrayList<>();
            }
            g[x].add(y);
        }
        

        
        LinkedList<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];
        queue.addLast(start);
        visited[start] = true;

        while(!queue.isEmpty()){
            int node = queue.removeFirst();

            //注意这一点,邻接表中可能存在以某个节点为根的链表不存在任何节点,
            //即这个节点的出度为0的情况,要单独考虑
            if(g[node] == null){
                continue;
            }
int size = g[node].size(); for(int j = 0;j<size;j++){ int nextNode = g[node].get(j); if(!visited[nextNode]){ if(nextNode == target){ return true; }else{ queue.addLast(nextNode); visited[nextNode] =true; } } } } return false; } }

 

posted @ 2020-11-29 23:18  3KBLACK  阅读(221)  评论(0)    收藏  举报