diff --git a/cpp/2204/220429.cpp b/cpp/2204/220429.cpp new file mode 100644 index 0000000..7b3592a --- /dev/null +++ b/cpp/2204/220429.cpp @@ -0,0 +1,47 @@ +#include +#include + +/** + * 785. Is Graph Bipartite? + * There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties: + * There are no self-edges (graph[u] does not contain u). + * There are no parallel edges (graph[u] does not contain duplicate values). + * If v is in graph[u], then u is in graph[v] (the graph is undirected). + * The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them. + * A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B. + * Return true if and only if it is bipartite. + */ + +class Solution { +public: + static bool isBipartite(const std::vector>& G) { + const int n = G.size(); + std::vector colour(n); + std::vector vis(n); + std::queue q; + + for (int i = 0; i < n; ++i) { + if (vis[i]) + continue; + q.push(i); + colour[i] = 1; + vis[i] = true; + while (!q.empty()) { + auto idx = q.front(); + q.pop(); + auto nextColour = colour[idx] ^ 3; + for (int idxNext : G[idx]) { + if (vis[idxNext]) { + if (colour[idxNext] != nextColour) + return false; + continue; + } + vis[idxNext] = true; + colour[idxNext] = nextColour; + q.push(idxNext); + } + } + } + return true; + } +}; diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index bec29b7..994dad8 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220428.cpp) +ADD_EXECUTABLE(2204 220429.cpp)