|
| 1 | +--- |
| 2 | +id: bfs-of-graph |
| 3 | +title: BFS of Graph |
| 4 | +sidebar_label: 8 BFS of Graph |
| 5 | +tags: |
| 6 | +- Graph |
| 7 | +- BFS |
| 8 | +- Python |
| 9 | +- Java |
| 10 | +- C++ |
| 11 | +- JavaScript |
| 12 | +- TypeScript |
| 13 | +description: "This document provides solutions to the problem of performing a Breadth First Search (BFS) traversal of a directed graph in various programming languages." |
| 14 | +--- |
| 15 | + |
| 16 | +## Problem |
| 17 | + |
| 18 | +Given a directed graph, perform a Breadth First Traversal starting from the 0th vertex. One can move from node `u` to node `v` only if there's an edge from `u` to `v`. Find the BFS traversal of the graph starting from the 0th vertex, from left to right according to the input graph. Only consider nodes that are directly or indirectly connected to node `0`. |
| 19 | + |
| 20 | +### Examples |
| 21 | + |
| 22 | +**Example 1:** |
| 23 | + |
| 24 | +``` |
| 25 | +Input: V = 5, E = 4, adj = {{1,2,3},{},{4},{},{}} |
| 26 | +Output: 0 1 2 3 4 |
| 27 | +Explanation: |
| 28 | +0 is connected to 1, 2, 3. |
| 29 | +2 is connected to 4. |
| 30 | +Starting from 0, it will go to 1 then 2 then 3. After this, 2 to 4, thus BFS will be 0 1 2 3 4. |
| 31 | +``` |
| 32 | + |
| 33 | +**Example 2:** |
| 34 | + |
| 35 | +``` |
| 36 | +Input: V = 3, E = 2, adj = {{1,2},{},{}} |
| 37 | +Output: 0 1 2 |
| 38 | +Explanation: |
| 39 | +0 is connected to 1, 2. |
| 40 | +Starting from 0, it will go to 1 then 2, thus BFS will be 0 1 2. |
| 41 | +``` |
| 42 | + |
| 43 | +### Your Task |
| 44 | + |
| 45 | +You don't need to read input or print anything. Your task is to complete the function `bfsOfGraph()` which takes the integer `V` denoting the number of vertices and adjacency list as input parameters and returns a list containing the BFS traversal of the graph starting from the 0th vertex from left to right. |
| 46 | + |
| 47 | +**Expected Time Complexity:** $O(V + E)$ |
| 48 | +**Expected Auxiliary Space:** $O(V)$ |
| 49 | + |
| 50 | +**Constraints** |
| 51 | +- $1 ≤ V, E ≤ 10^4$ |
| 52 | + |
| 53 | +## Solution |
| 54 | + |
| 55 | +### Intuition & Approach |
| 56 | + |
| 57 | +Breadth First Search (BFS) is a method to traverse a graph level by level, starting from a given node. We use a queue data structure to facilitate this traversal. The main steps are: |
| 58 | + |
| 59 | +1. Create a boolean list `visited` to mark all vertices as not visited. |
| 60 | +2. Initialize the traversal from the starting vertex (0th vertex). |
| 61 | +3. Use a queue to explore nodes level by level, marking each node as visited once it is processed. |
| 62 | +4. For each node, explore its adjacent vertices that have not been visited yet, marking them as visited and adding them to the queue. |
| 63 | +5. Continue this process until the queue is empty. |
| 64 | + |
| 65 | +### Implementation |
| 66 | + |
| 67 | +<Tabs> |
| 68 | + <TabItem value="python" label="Python"> |
| 69 | + |
| 70 | +```python |
| 71 | +from collections import deque |
| 72 | + |
| 73 | +class Solution: |
| 74 | + |
| 75 | + def bfsOfGraph(self, V, adj): |
| 76 | + visited = [False] * V |
| 77 | + queue = deque([0]) |
| 78 | + visited[0] = True |
| 79 | + result = [] |
| 80 | + |
| 81 | + while queue: |
| 82 | + node = queue.popleft() |
| 83 | + result.append(node) |
| 84 | + for neighbor in adj[node]: |
| 85 | + if not visited[neighbor]: |
| 86 | + queue.append(neighbor) |
| 87 | + visited[neighbor] = True |
| 88 | + return result |
| 89 | +``` |
| 90 | + |
| 91 | + </TabItem> |
| 92 | + <TabItem value="java" label="Java"> |
| 93 | + |
| 94 | +```java |
| 95 | +import java.util.ArrayList; |
| 96 | +import java.util.LinkedList; |
| 97 | +import java.util.Queue; |
| 98 | + |
| 99 | +class Solution { |
| 100 | + public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) { |
| 101 | + ArrayList<Integer> traversal = new ArrayList<>(); |
| 102 | + Queue<Integer> queue = new LinkedList<>(); |
| 103 | + boolean[] visited = new boolean[V]; |
| 104 | + queue.add(0); |
| 105 | + visited[0] = true; |
| 106 | + |
| 107 | + while (!queue.isEmpty()) { |
| 108 | + int node = queue.poll(); |
| 109 | + traversal.add(node); |
| 110 | + for (int neighbor : adj.get(node)) { |
| 111 | + if (!visited[neighbor]) { |
| 112 | + queue.add(neighbor); |
| 113 | + visited[neighbor] = true; |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + return traversal; |
| 118 | + } |
| 119 | +} |
| 120 | +``` |
| 121 | + |
| 122 | + </TabItem> |
| 123 | + <TabItem value="cpp" label="C++"> |
| 124 | + |
| 125 | +```cpp |
| 126 | +#include <vector> |
| 127 | +#include <queue> |
| 128 | + |
| 129 | +class Solution { |
| 130 | +public: |
| 131 | + std::vector<int> bfsOfGraph(int V, std::vector<int> adj[]) { |
| 132 | + std::vector<int> result; |
| 133 | + std::vector<bool> visited(V, false); |
| 134 | + std::queue<int> q; |
| 135 | + |
| 136 | + q.push(0); |
| 137 | + visited[0] = true; |
| 138 | + |
| 139 | + while (!q.empty()) { |
| 140 | + int node = q.front(); |
| 141 | + q.pop(); |
| 142 | + result.push_back(node); |
| 143 | + for (int neighbor : adj[node]) { |
| 144 | + if (!visited[neighbor]) { |
| 145 | + q.push(neighbor); |
| 146 | + visited[neighbor] = true; |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + return result; |
| 151 | + } |
| 152 | +}; |
| 153 | +``` |
| 154 | +
|
| 155 | + </TabItem> |
| 156 | + <TabItem value="javascript" label="JavaScript"> |
| 157 | +
|
| 158 | +```javascript |
| 159 | +class Solution { |
| 160 | + bfsOfGraph(V, adj) { |
| 161 | + let visited = new Array(V).fill(false); |
| 162 | + let queue = [0]; |
| 163 | + visited[0] = true; |
| 164 | + let result = []; |
| 165 | + |
| 166 | + while (queue.length > 0) { |
| 167 | + let node = queue.shift(); |
| 168 | + result.push(node); |
| 169 | + for (let neighbor of adj[node]) { |
| 170 | + if (!visited[neighbor]) { |
| 171 | + queue.push(neighbor); |
| 172 | + visited[neighbor] = true; |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | + return result; |
| 177 | + } |
| 178 | +} |
| 179 | +``` |
| 180 | + |
| 181 | + </TabItem> |
| 182 | + <TabItem value="typescript" label="TypeScript"> |
| 183 | + |
| 184 | +```typescript |
| 185 | +class Solution { |
| 186 | + bfsOfGraph(V: number, adj: number[][]): number[] { |
| 187 | + let visited = new Array(V).fill(false); |
| 188 | + let queue: number[] = [0]; |
| 189 | + visited[0] = true; |
| 190 | + let result: number[] = []; |
| 191 | + |
| 192 | + while (queue.length > 0) { |
| 193 | + let node = queue.shift() as number; |
| 194 | + result.push(node); |
| 195 | + for (let neighbor of adj[node]) { |
| 196 | + if (!visited[neighbor]) { |
| 197 | + queue.push(neighbor); |
| 198 | + visited[neighbor] = true; |
| 199 | + } |
| 200 | + } |
| 201 | + } |
| 202 | + return result; |
| 203 | + } |
| 204 | +} |
| 205 | +``` |
| 206 | + |
| 207 | + </TabItem> |
| 208 | +</Tabs> |
| 209 | + |
| 210 | +--- |
| 211 | + |
| 212 | +## Complexity analysis |
| 213 | + |
| 214 | +The provided solutions efficiently perform a Breadth First Search (BFS) traversal of a directed graph. By starting from the 0th vertex and using a queue to manage the traversal, the algorithms ensure that all reachable vertices are visited in the correct order. The solutions operate in $O(V + E)$ time and use $O(V)$ space complexity, where V and E are the numbers of vertices and edges in the graph, respectively. |
| 215 | + |
| 216 | +**Time Complexity:** $O(V + E)$ |
| 217 | +**Auxiliary Space:** $O(V)$ |
| 218 | + |
| 219 | +## References |
| 220 | + |
| 221 | +- **GeeksforGeeks Problem:** [BFS of graph](https://www.geeksforgeeks.org/problems/bfs-traversal-of-graph/0) |
| 222 | +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) |
0 commit comments