8.Is Graph Bipartite?
Given an undirected graph
, return true
if and only if it is bipartite.
class Solution
{
public:
bool checkBipartite(vector<vector<int>> &graph, int node, vector<bool> &vs, vector<int> &color)
{
queue<int> q;
q.push(node);
vs[node] = 1;
color[node] = 1;
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = 0; i < graph[x].size(); i++)
{
if (vs[graph[x][i]] == 0)
{
vs[graph[x][i]] = 1;
q.push(graph[x][i]);
color[graph[x][i]] = 1 - color[x];
}
else
{
if (color[graph[x][i]] == color[x])
{
return false;
}
}
}
}
return true;
}
bool isBipartite(vector<vector<int>> &graph)
{
int n = graph.size();
vector<bool> vs(n);
vector<int> color(n, -1);
for (int i = 0; i < n; i++)
{
if (vs[i] == 0)
{
if (!checkBipartite(graph, i, vs, color))
{
return false;
}
}
}
return true;
}
};
Last updated