CPP BFS solution Time complexity O(V+E) Space Complexity O(V)
| 2 | //Time complexity O(V+E) |
| 3 | //Space Complexity O(V) |
| 4 | class Solution { |
| 5 | public: |
| 6 | bool isBipartite(vector<vector<int>>& graph) { |
| 7 | int n=graph.size(); |
| 8 | vector<bool>v(n,false); |
| 9 | vector<int>c(n,-1); |
| 10 | queue<int>q; |
| 11 | |
| 12 | for(int i=0;i<n;i++){ |
| 13 | if(v[i]||graph[i].size()==0){ |
| 14 | continue; |
| 15 | } |
| 16 | q.push(i); |
| 17 | v[i]=true; |
| 18 | c[i]=1; |
| 19 | while(!q.empty()){ |
| 20 | int j=q.front(); |
| 21 | q.pop(); |
| 22 | for(int k=0;k<graph[j].size();k++){ |
| 23 | if(c[graph[j][k]]==-1){ |
| 24 | c[graph[j][k]]=1-c[j]; |
| 25 | q.push(graph[j][k]); |
| 26 | v[graph[j][k]]=true; |
| 27 | } |
| 28 | else if(c[j]==c[graph[j][k]]){ |
| 29 | return false; |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | } |
| 35 | return true; |
| 36 | |
| 37 | |
| 38 | } |
| 39 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected