-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay41.java
More file actions
59 lines (47 loc) · 2.12 KB
/
Copy pathDay41.java
File metadata and controls
59 lines (47 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*BFS of graph
Given a connected undirected graph containing V vertices, represented by a 2-d adjacency list adj[][], where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the given adjacency list, and return a list containing the BFS traversal of the graph.
Note: Do traverse in the same order as they are in the given adjacency list.
Examples:
Input: adj[][] = [[2, 3, 1], [0], [0, 4], [0], [2]]
Output: [0, 2, 3, 1, 4]
Explanation: Starting from 0, the BFS traversal will follow these steps:
Visit 0 → Output: 0
Visit 2 (first neighbor of 0) → Output: 0, 2
Visit 3 (next neighbor of 0) → Output: 0, 2, 3
Visit 1 (next neighbor of 0) → Output: 0, 2, 3, 1
Visit 4 (neighbor of 2) → Final Output: 0, 2, 3, 1, 4
Input: adj[][] = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
Output: [0, 1, 2, 3, 4]
Explanation: Starting from 0, the BFS traversal proceeds as follows:
Visit 0 → Output: 0
Visit 1 (the first neighbor of 0) → Output: 0, 1
Visit 2 (the next neighbor of 0) → Output: 0, 1, 2
Visit 3 (the first neighbor of 2 that hasn't been visited yet) → Output: 0, 1, 2, 3
Visit 4 (the next neighbor of 2) → Final Output: 0, 1, 2, 3, 4 */
/* class Solution {
public ArrayList<Integer> bfs(ArrayList<ArrayList<Integer>> adj) {
ArrayList<Integer> bfs = new ArrayList<>();
int V = adj.size();
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
// Start BFS from vertex 0
visited[0] = true;
queue.add(0);
while (!queue.isEmpty()) {
int node = queue.poll();
bfs.add(node);
// Traverse neighbors left to right
for (int neighbour : adj.get(node)) {
if (!visited[neighbour]) {
visited[neighbour] = true;
queue.add(neighbour);
}
}
}
return bfs;
}
}
*/
/* ⏱ Time & Space Complexity
Time: O(V + E)
Space: O(V)*/