Skip to content

Commit 7731743

Browse files
authored
Create main.cpp
1 parent 8ecdedd commit 7731743

File tree

1 file changed

+30
-0
lines changed
  • 23 - Graph Data Structure Problems/05 - BFS of Graph

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
// Function to return Breadth First Traversal of given graph.
4+
vector<int> bfsOfGraph(vector<vector<int>> &adj) {
5+
int V = adj.size();
6+
vector<int> result;
7+
vector<bool> visited(V, false);
8+
queue<int> q;
9+
10+
q.push(0);
11+
visited[0] = true;
12+
13+
while(!q.empty()){
14+
int currentNode = q.front();
15+
q.pop();
16+
17+
result.push_back(currentNode);
18+
19+
for(int neighbor : adj[currentNode]){
20+
if(!visited[neighbor]){
21+
q.push(neighbor);
22+
visited[neighbor] = true;
23+
}
24+
}
25+
}
26+
27+
return result;
28+
29+
}
30+
};

0 commit comments

Comments
 (0)