Created
February 5, 2022 15:38
-
-
Save arsho/5a0e8670b328909b22b94069e157de5d to your computer and use it in GitHub Desktop.
Basic BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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