Leetcode 785. Is Graph Bipartite?
You are given an undirected
graph represented as a 2D array of integers graph
, where graph[i]
is a list of integers representing the nodes that node i
is directly connected to. Determine if the given graph is a bipartite graph.
To determine if a graph is bipartite, we need to check if we can color the graph using two colors in such a way that no two adjacent nodes have the same color. This can be approached using a Breadth-First Search (BFS) or Depth-First Search (DFS).
#include <vector>
#include <queue>
class Solution {
public:
bool isBipartite(std::vector<std::vector<int>>& graph) {
int n = graph.size();
std::vector<int> colors(n, -1);
// Iterate over all nodes to ensure we handle disconnected components
for (int i = 0; i < n; i++) {
if (colors[i] == -1) {
if (!bfsCheck(graph, colors, i)) {
return false;
}
}
}
return true;
}
private:
bool bfsCheck(const std::vector<std::vector<int>>& graph, std::vector<int>& colors, int start) {
std::queue<int> q;
q.push(start);
colors[start] = 0; // Start coloring the first node with color 0
while (!q.empty()) {
int node = q.front();
q.pop();
// Check all adjacent nodes
for (int neighbor : graph[node]) {
if (colors[neighbor] == -1) {
// Color the neighbor with the opposite color of the current node
colors[neighbor] = 1 - colors[node];
q.push(neighbor);
} else if (colors[neighbor] == colors[node]) {
// An adjacent node has the same color
return false;
}
}
}
return true;
}
};
This approach ensures that we correctly determine if the graph is bipartite by attempting to color it using a BFS strategy and checking all nodes and edges efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?