|
| 1 | +package src.algorithms.graphs; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +import src.algorithms.graphs.util.BinaryTreeNode; |
| 6 | +import src.algorithms.graphs.util.GraphNode; |
| 7 | + |
| 8 | +/** |
| 9 | + * Implementation of BFS |
| 10 | + * |
| 11 | + * Breadth-First search is a graph traversal algorithm that utilizes a queue (FIFO) data structure |
| 12 | + * It is useful in finding a shortest-hops solution in graphs |
| 13 | + * This method is also used to obtain level order traversals of trees. |
| 14 | + * |
| 15 | + * In general, BFS works as such: |
| 16 | + * - Start with a queue that contains the root node |
| 17 | + * - While the queue is not empty: |
| 18 | + * - Pop a vertex from the queue |
| 19 | + * - Push all neighbours to the queue if they have not been visited yet |
| 20 | + * - Update any variables as needed |
| 21 | + * |
| 22 | + * Time: O(V + E), where V is the number of vertices/nodes, and E is the number of edges in the graph |
| 23 | + * Explanation: Each vertex is popped in O(1) time from the stack exactly once, hence O(V) |
| 24 | + * For each edge, we must check in O(1) time if we have visited the adjacent vertex to know |
| 25 | + * whether to push it into the queue, hence O(E). |
| 26 | + * Note that if the graph is a forest, BFS will likely terminate earlier, as fewer vertices are traversed |
| 27 | + * |
| 28 | + * Space: O(V): We utilize a Hashset to store the vertices we have visited already. In the worst case we have a |
| 29 | + * connected graph where all vertices are traversed, and our Hashset stores all O(V) vertices. |
| 30 | + * Further, we use a queue to hold the vertices to be traversed. In the worst case, the root will have all |
| 31 | + * other vertices as neighbours, and our queue will contain O(V) vertices. |
| 32 | + * |
| 33 | + * ** Note: The above description assumes an adjacency list in order to consider neighbours in an efficient manner |
| 34 | + * If an adjacency matrix were used, it would cost O(V) to find neighbours for a single vertex, making our |
| 35 | + * average case time complexity O(V^2) for a connected graph |
| 36 | + * |
| 37 | + * The implementation demonstrates the use of BFS in finding the level-order (Root, Left, Right) traversal of a binary tree |
| 38 | + * The tree is represented using a custom BinaryTreeNode class |
| 39 | + * |
| 40 | + */ |
| 41 | +public class breadthFirstSearch { |
| 42 | + |
| 43 | + // Prints level order traversal from left to right |
| 44 | + public static List<Integer> levelOrder(BinaryTreeNode root) { |
| 45 | + if (root == null) { return new ArrayList<>(); } |
| 46 | + List<Integer> traversal = new ArrayList<>(); |
| 47 | + Queue<BinaryTreeNode> queue = new LinkedList<>(); |
| 48 | + queue.add(root); |
| 49 | + |
| 50 | + while (!queue.isEmpty()) { |
| 51 | + BinaryTreeNode curr = queue.remove(); |
| 52 | + traversal.add((Integer) curr.getVal()); |
| 53 | + if (curr.getLeft() != null) { queue.add(curr.getLeft()); } |
| 54 | + if (curr.getRight() != null) { queue.add(curr.getRight()); } |
| 55 | + } |
| 56 | + |
| 57 | + return traversal; |
| 58 | + } |
| 59 | + |
| 60 | + // Finds the number of friend hops needed to go from person A to person B |
| 61 | + // Uses GraphNode<String>, where a node holds a String of the persons name, and an edge represents a friendship |
| 62 | + public static int friendHops(GraphNode<String> personA, GraphNode<String> personB) { |
| 63 | + // Hashset to store the people we have seen already |
| 64 | + HashSet<GraphNode> checked = new HashSet<>(); |
| 65 | + // Hashmap to remember how many hops were needed to get to a specific friend * |
| 66 | + HashMap<GraphNode, Integer> map = new HashMap<>(); |
| 67 | + |
| 68 | + Queue<GraphNode> queue = new LinkedList<>(); |
| 69 | + queue.add(personA); |
| 70 | + // the number of hops to the person themselves is 0, so we map: personA -> 0 |
| 71 | + map.put(personA, 0); |
| 72 | + int hops = 0; |
| 73 | + |
| 74 | + while (!queue.isEmpty()) { |
| 75 | + // poll the queue to get the next person to consider |
| 76 | + GraphNode<String> currPerson = queue.remove(); |
| 77 | + // add the person to the checked hashset so we don't consider them again |
| 78 | + checked.add(currPerson); |
| 79 | + // grab the number of hops from the hashmap and add 1 |
| 80 | + hops = map.get(currPerson) + 1; |
| 81 | + |
| 82 | + List<GraphNode> neighbours = currPerson.neighbours(); |
| 83 | + for (GraphNode neighbour : neighbours) { |
| 84 | + if (neighbour == personB) { return hops; } |
| 85 | + if (!checked.contains(neighbour)) { |
| 86 | + queue.add(neighbour); |
| 87 | + map.put(neighbour, hops); |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + // Returns -1 if person not found |
| 92 | + return -1; |
| 93 | + |
| 94 | + // * Note that we can actually use just the hashmap instead of both the hashmap and the hashset! |
| 95 | + // This is because the hashmap supports the map.containsKey() function. |
| 96 | + } |
| 97 | + |
| 98 | + public static int friendHopsVisualize(GraphNode<String> personA, GraphNode<String> personB) { |
| 99 | + // Hashset to store the people we have seen already |
| 100 | + HashSet<GraphNode> checked = new HashSet<>(); |
| 101 | + // Hashmap to remember how many hops were needed to get to a specific friend * |
| 102 | + HashMap<GraphNode, Integer> map = new HashMap<>(); |
| 103 | + |
| 104 | + Queue<GraphNode> queue = new LinkedList<>(); |
| 105 | + queue.add(personA); |
| 106 | + // the number of hops to the person themselves is 0, so we map: personA -> 0 |
| 107 | + map.put(personA, 0); |
| 108 | + int hops = 0; |
| 109 | + |
| 110 | + while (!queue.isEmpty()) { |
| 111 | + System.out.println("Current queue: " + String.valueOf(queue) + ", current hops: " + hops); |
| 112 | + // poll the queue to get the next person to consider |
| 113 | + GraphNode<String> currPerson = queue.remove(); |
| 114 | + // add the person to the checked hashset so we don't consider them again |
| 115 | + checked.add(currPerson); |
| 116 | + // grab the number of hops from the hashmap and add 1 |
| 117 | + hops = map.get(currPerson) + 1; |
| 118 | + |
| 119 | + System.out.println("Looking at friends of: " + currPerson.toString()); |
| 120 | + List<GraphNode> neighbours = currPerson.neighbours(); |
| 121 | + for (GraphNode neighbour : neighbours) { |
| 122 | + if (neighbour == personB) { return hops; } |
| 123 | + if (!checked.contains(neighbour)) { |
| 124 | + queue.add(neighbour); |
| 125 | + map.put(neighbour, hops); |
| 126 | + } |
| 127 | + } |
| 128 | + System.out.println("Current queue: " + String.valueOf(queue) + ", current hops: " + hops); |
| 129 | + } |
| 130 | + // Returns -1 if person not found |
| 131 | + return -1; |
| 132 | + } |
| 133 | +} |
0 commit comments