Skip to content

Instantly share code, notes, and snippets.

@arsho
Created February 5, 2022 15:38
Show Gist options
  • Save arsho/5a0e8670b328909b22b94069e157de5d to your computer and use it in GitHub Desktop.
Save arsho/5a0e8670b328909b22b94069e157de5d to your computer and use it in GitHub Desktop.
Basic BFS
class Solution {
// Function to return Breadth First Traversal of given graph.
public ArrayList < Integer > bfsOfGraph(int V, ArrayList < ArrayList < Integer >> adj) {
ArrayList < Integer > ans = new ArrayList < Integer > ();
int[] color = new int[V];
color[0] = 1;
Queue < Integer > q = new LinkedList < > ();
q.add(0);
ans.add(0);
while (q.size() != 0) {
int u = q.remove();
for (int v: adj.get(u)) {
if (color[v] == 0) {
q.add(v);
ans.add(v);
color[v] = 1;
}
}
}
return ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment