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();
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 文:哈哈世界 Q聊竟然偶遇同門師弟,不覺同聲感嘆:“世界真小??!”與師弟閑聊,勾起對二十年前校園生活的回憶,那些在...
    哈哈世界123閱讀 404評論 0 1
  • Christmas Market 開始了~
    四月晴天的日志閱讀 269評論 0 0
  • 今年婆婆80歲了。 大家商量著要給老媽辦80大壽。婆婆的妹妹、弟弟早就說好了,要來姐姐家賀壽。我和老公繞道接來了婆...
    花香兩岸閱讀 325評論 1 2
  • 前些日子,聽朋友談起《煮酒探西游》這本書,起先覺得有趣,于是就看了看,可后來發(fā)現(xiàn)越看越離譜,這本書已經把吳承恩的原...
    糖點什么閱讀 646評論 0 1

友情鏈接更多精彩內容