Skip to content

Instantly share code, notes, and snippets.

@javrasya
Created June 30, 2019 22:27
Show Gist options
  • Save javrasya/502c86d5877f876b8f059f4150edd197 to your computer and use it in GitHub Desktop.
Save javrasya/502c86d5877f876b8f059f4150edd197 to your computer and use it in GitHub Desktop.
import java.util.*;
public class MyTest {
private static int shortestPath(int[] from, int[] to, int source, int destination) {
Map<Integer, Set<Integer>> graph = getGraph(from, to);
return iterate(graph, new HashSet<>(), source, destination);
}
private static Map<Integer, Set<Integer>> getGraph(int[] from, int[] to) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 0; i < from.length; i++) {
Set<Integer> neighbourhood = graph.getOrDefault(from[i], new HashSet<>());
neighbourhood.add(to[i]);
graph.put(from[i], neighbourhood);
}
for (int i = 0; i < to.length; i++) {
Set<Integer> neighbourhood = graph.getOrDefault(to[i], new HashSet<>());
neighbourhood.add(from[i]);
graph.put(to[i], neighbourhood);
}
return graph;
}
private static int iterate(Map<Integer, Set<Integer>> graph, Set<Integer> seenNodes, Integer node, Integer destination) {
seenNodes.add(node);
Set<Integer> neighbours = graph.get(node);
for (Integer neighbour : neighbours) {
if (!seenNodes.contains(neighbour) && neighbour.equals(destination)) {
return 1;
}
}
for (Integer neighbour : neighbours) {
if (!seenNodes.contains(neighbour)) {
int distance = iterate(graph, seenNodes, neighbour, destination);
if (distance != -1) {
return distance + 1;
}
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(shortestPath(new int[]{0, 0, 1}, new int[]{1, 2, 3}, 2, 3));
// System.out.println(shortestPath(new int[]{0, 1}, new int[]{2, 3}, 0, 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment