Skip to content

Instantly share code, notes, and snippets.

@pungrue26
Created October 24, 2016 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pungrue26/3e695f971011f2ebf9c430b9a11cec46 to your computer and use it in GitHub Desktop.
Save pungrue26/3e695f971011f2ebf9c430b9a11cec46 to your computer and use it in GitHub Desktop.
Breadth First Search: Shortest Reach
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
int m = in.nextInt();
int from, to;
HashMap<Integer, Set<Integer>> map = new HashMap<>();
for (int j = 0; j < m; j++) {
from = in.nextInt();
// System.out.println("from : " + from);
to = in.nextInt();
// System.out.println("to : " + to);
if (map.containsKey(from)) {
Set<Integer> list = map.get(from);
list.add(to);
map.put(from, list);
} else {
map.put(from, new HashSet<Integer>(Arrays.asList(to)));
}
if (map.containsKey(to)) {
Set<Integer> list = map.get(to);
list.add(from);
map.put(to, list);
} else {
map.put(to, new HashSet<Integer>(Arrays.asList(from)));
}
}
int s = in.nextInt();
printShortest(s, n, map);
}
in.close();
}
private static void printShortest(int s, int n, Map<Integer, Set<Integer>> map) {
int [] distance = new int [n];
HashSet<Integer> visited = new HashSet<>();
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (!q.isEmpty()) {
int v = q.remove();
if (visited.contains(v)) {
continue;
} else {
visited.add(v);
Set<Integer> set = map.get(v);
if (set != null) {
q.addAll(set);
for (Integer i : set) {
if (distance [i - 1] == 0)
distance[i - 1] = distance[v - 1] + 6;
}
}
}
}
for (int i = 0; i < n; i++) {
if (i == s - 1) {
continue;
} else {
if (distance[i] == 0) {
System.out.print(-1);
} else {
System.out.print(distance[i]);
}
}
System.out.print(i == n - 1? "\n" : ' ');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment