




Sponsored
Sponsored
This approach uses breadth-first search (BFS) to try and color the graph using two colors, validating its bipartiteness. By starting at any unvisited node and attempting to color it with one color, you color all its neighbors with an alternating color. If at any point a neighbor is found to already have the same color, then the graph cannot be bipartite.
The time complexity is O(V + E) where V is the number of vertices and E is the number of edges, as each edge and vertex is visited once in BFS. The space complexity is O(V) due to the storage needed for the color array and the BFS queue.
1#include <iostream>
2#include <vector>
3#include <queue>
4using namespace std;
5
6bool bfsCheck(int start, vector<vector<int>>& graph, vector<int>& colors) {
7    queue<int> q;
8    q.push(start);
9    colors[start] = 0;
10    
11    while (!q.empty()) {
12        int node = q.front();
13        q.pop();
14
15        for (int neighbor : graph[node]) {
16            if (colors[neighbor] == -1) {
17                colors[neighbor] = 1 - colors[node];
18                q.push(neighbor);
19            } else if (colors[neighbor] == colors[node]) {
20                return false;
21            }
22        }
23    }
24    return true;
25}
26
27bool isBipartite(vector<vector<int>>& graph) {
28    int n = graph.size();
29    vector<int> colors(n, -1);
30    
31    for (int i = 0; i < n; ++i) {
32        if (colors[i] == -1) {
33            if (!bfsCheck(i, graph, colors)) {
34                return false;
35            }
36        }
37    }
38    return true;
39}
40
41int main() {
42    vector<vector<int>> graph = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};
43    cout << (isBipartite(graph) ? "true" : "false") << endl;
44    return 0;
45}In this C++ implementation, the graph is represented using an adjacency list (vector of vectors). The bfsCheck function is responsible for conducting a BFS on unvisited nodes, trying to color adjacent nodes with alternating colors. A same-color conflict during the traversal indicates the graph is non-bipartite.
The depth-first search (DFS) approach is an alternative to BFS for examining bipartiteness. You use DFS recursively to color the graph and check for conflicts. The method still involves checking whether adjacent nodes have opposing colors, iterating through components one by one as needed.
The time complexity is O(V + E), and the space complexity is O(V) due to recursive depth stack space utilization.
1
        
The Java implementation adopts DFS via a recursive function in similar fashion. It systematically visits nodes and attempts to color them oppositely, reverting where necessary after a failed condition.