BFS: Shortest Reach in a Graph

Check out the resources on the page's right side to learn more about breadth-first search. The video tutorial is by Gayle Laakmann McDowell, author of the best-selling interview book Cracking the Coding Interview.

Consider an undirected graph consisting of n nodes where each node is labeled from 1 to n and the edge between any two nodes is always of length 6. We define node s to be the starting position for a BFS.

Given q queries in the form of a graph and some starting node, s , perform each query by calculating the shortest distance from starting node s to all the other nodes in the graph. Then print a single line of n-1 space-separated integers listing node s's shortest distance to each of the n-1 other nodes (ordered sequentially by node number); if s is disconnected from a node, print -1 as the distance to that node.

Input Format
The first line contains an integer, q, denoting the number of queries. The subsequent lines describe each query in the following format:

  • The first line contains two space-separated integers describing the respective values of n(the number of nodes) and m(the number of edges) in the graph.
  • Each line i of the m subsequent lines contains two space separated integers, u and v , describing an edge connecting node u to node v.
  • The last line contains a single integer, s, denoting the index of the starting node.

Constraints

Output Format
For each of the q queries, print a single line of n-1 space-separated integers denoting the shortest distances to each of the n-1 other nodes from starting position s. These distances should be listed sequentially by node number (i.e.), but should not include node s. If some node is unreachable from s, print -1 as the distance to that node.
Sample Input

2
4 2
1 2
1 3
1
3 1
2 3
2

Sample Output

6 6 -1
-1 6

Explanation
We perform the following two queries:

  1. The given graph can be represented as:


    image.png

where our start node, s, is node 1. The shortest distances from
s to the other nodes are one edge to node 2, one edge to node 3, and an infinite distance to node 4(which it's not connected to). We then print node 1's distance to nodes 2, 3, and 4(respectively) as a single line of space-separated integers: 6 6 -1.

  1. The given graph can be represented as:


    image.png

where our start node, s, is node 2. There is only one edge here, so node 1 is unreachable from node 2 and node 3 has one edge connecting it to node 2. We then print node 2's distance to nodes 1and 3(respectively) as a single line of space-separated integers: -1 6.
Note: Recall that the actual length of each edge is
6, and we print -1 as the distance to any node that's unreachable from s.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static class Graph {
        List<List<Integer>> adjList;
        int size;
        
        public Graph(int size) {
            adjList = new ArrayList<>();
            this.size = size;
            while(size-- >0){
                adjList.add(new ArrayList<Integer>());
            }
        }

        public void addEdge(int first, int second) {
            // undirected graph, you gotta add for both nodes.
            adjList.get(first).add(second);
            adjList.get(second).add(first);
        }
        
        public int[] shortestReach(int startId) { // 0 indexed
            int[] distances = new int[size];
            Arrays.fill(distances,-1);// fill array with -1
            Queue<Integer> q = new LinkedList<>();
            HashSet<Integer> seen = new HashSet<>();
            q.add(startId);
            distances[startId] = 0;
            while(!q.isEmpty()){
                Integer current = q.poll();
                for(Integer node:adjList.get(current)){
                    if(!seen.contains(node)){
                        q.offer(node);
                        seen.add(node);
                        distances[node] = distances[current] + 6;
                    }
                }
            }
            return distances;
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
      
        int queries = scanner.nextInt();
        
        for (int t = 0; t < queries; t++) {
            
            // Create a graph of size n where each edge weight is 6:
            Graph graph = new Graph(scanner.nextInt());
            int m = scanner.nextInt();
            
            // read and set edges
            for (int i = 0; i < m; i++) {
                int u = scanner.nextInt() - 1;
                int v = scanner.nextInt() - 1;
                
                // add each edge to the graph
                graph.addEdge(u, v);
            }
            
            // Find shortest reach from node s
            int startId = scanner.nextInt() - 1;
            int[] distances = graph.shortestReach(startId);
 
            for (int i = 0; i < distances.length; i++) {
                if (i != startId) {
                    System.out.print(distances[i]);
                    System.out.print(" ");
                }
            }
            System.out.println();            
        }
        
        scanner.close();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文:哈哈世界 Q聊竟然偶遇同门师弟,不觉同声感叹:“世界真小啊!”与师弟闲聊,勾起对二十年前校园生活的回忆,那些在...
    哈哈世界123阅读 362评论 0 1
  • Christmas Market 开始了~
    四月晴天的日志阅读 235评论 0 0
  • 今年婆婆80岁了。 大家商量着要给老妈办80大寿。婆婆的妹妹、弟弟早就说好了,要来姐姐家贺寿。我和老公绕道接来了婆...
    花香两岸阅读 275评论 1 2
  • 前些日子,听朋友谈起《煮酒探西游》这本书,起先觉得有趣,于是就看了看,可后来发现越看越离谱,这本书已经把吴承恩的原...
    糖点什么阅读 565评论 0 1