|
1 | 1 | package com.ctci.treesandgraphs;
|
2 | 2 |
|
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Queue; |
| 8 | +import java.util.Set; |
| 9 | + |
3 | 10 | /**
|
4 | 11 | * @author rampatra
|
5 | 12 | * @since 2019-03-21
|
6 | 13 | */
|
7 | 14 | public class RouteBetweenNodes {
|
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + Graph g = new Graph(); |
| 18 | + g.addEdge(1, 2); |
| 19 | + g.addEdge(2, 3); |
| 20 | + g.addEdge(4, 5); |
| 21 | + g.addEdge(5, 6); |
| 22 | + System.out.println("Route exists from 1 to 2: " + g.isRoutePresent(1, 2)); |
| 23 | + System.out.println("Route exists from 2 to 5: " + g.isRoutePresent(2, 5)); |
| 24 | + System.out.println("Route exists from 1 to 3: " + g.isRoutePresent(1, 3)); |
| 25 | + System.out.println("Route exists from 4 to 6: " + g.isRoutePresent(4, 6)); |
| 26 | + System.out.println("Route exists from 6 to 4: " + g.isRoutePresent(6, 4)); |
| 27 | + System.out.println("Route exists from 6 to 5: " + g.isRoutePresent(6, 5)); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class Graph { |
| 32 | + |
| 33 | + private static final Map<Integer, GraphNode> nodes = new HashMap<>(); |
| 34 | + |
| 35 | + void addEdge(int v1, int v2) { |
| 36 | + GraphNode n1 = nodes.get(v1); |
| 37 | + GraphNode n2 = nodes.get(v2); |
| 38 | + |
| 39 | + if (n1 == null) { |
| 40 | + n1 = new GraphNode(v1); |
| 41 | + nodes.put(v1, n1); |
| 42 | + } |
| 43 | + if (n2 == null) { |
| 44 | + n2 = new GraphNode(v2); |
| 45 | + nodes.put(v2, n2); |
| 46 | + } |
| 47 | + |
| 48 | + n1.adjacent.add(n2); // as it is a directed graph |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Checks for a path from a node with value {@code v1} to another node with value {@code v2} in a breadth-first |
| 53 | + * manner. |
| 54 | + * |
| 55 | + * @param v1 the value of the first node or starting node. |
| 56 | + * @param v2 the value of the ending node. |
| 57 | + * @return {@code true} if path exists, {@code false} otherwise. |
| 58 | + */ |
| 59 | + boolean isRoutePresent(int v1, int v2) { |
| 60 | + Queue<GraphNode> queue = new ArrayDeque<>(); |
| 61 | + Set<GraphNode> visited = new HashSet<>(); |
| 62 | + |
| 63 | + GraphNode n1 = nodes.get(v1); |
| 64 | + GraphNode n2 = nodes.get(v2); |
| 65 | + |
| 66 | + if (n1 == null || n2 == null) { |
| 67 | + return false; |
| 68 | + } |
| 69 | + |
| 70 | + queue.add(n1); |
| 71 | + |
| 72 | + while (!queue.isEmpty()) { |
| 73 | + GraphNode n = queue.poll(); |
| 74 | + |
| 75 | + if (visited.contains(n)) { |
| 76 | + continue; |
| 77 | + } |
| 78 | + if (n.adjacent.contains(n2)) { |
| 79 | + return true; |
| 80 | + } |
| 81 | + queue.addAll(n.adjacent); |
| 82 | + visited.add(n); |
| 83 | + } |
| 84 | + |
| 85 | + return false; |
| 86 | + } |
8 | 87 | }
|
0 commit comments