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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容

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