|
| 1 | +/* |
| 2 | +Is Graph Bipartite? |
| 3 | +=================== |
| 4 | +
|
| 5 | +Given an undirected graph, return true if and only if it is bipartite. |
| 6 | +
|
| 7 | +Recall that a graph is bipartite if we can split its set of nodes into two independent subsets A and B, such that every edge in the graph has one node in A and another node in B. |
| 8 | +
|
| 9 | +The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: graph = [[1,3],[0,2],[1,3],[0,2]] |
| 13 | +Output: true |
| 14 | +Explanation: We can divide the vertices into two groups: {0, 2} and {1, 3}. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]] |
| 18 | +Output: false |
| 19 | +Explanation: We cannot find a way to divide the set of nodes into two independent subsets. |
| 20 | +
|
| 21 | +Constraints: |
| 22 | +1 <= graph.length <= 100 |
| 23 | +0 <= graph[i].length < 100 |
| 24 | +0 <= graph[i][j] <= graph.length - 1 |
| 25 | +graph[i][j] != i |
| 26 | +All the values of graph[i] are unique. |
| 27 | +The graph is guaranteed to be undirected. |
| 28 | +*/ |
| 29 | + |
| 30 | +class Solution |
| 31 | +{ |
| 32 | +public: |
| 33 | + bool bfs(int curr, vector<vector<int>> &graph, vector<int> &color) |
| 34 | + { |
| 35 | + queue<int> pending; |
| 36 | + pending.push(curr); |
| 37 | + color[curr] = 1; |
| 38 | + |
| 39 | + while (pending.size()) |
| 40 | + { |
| 41 | + auto curr = pending.front(); |
| 42 | + pending.pop(); |
| 43 | + for (auto &i : graph[curr]) |
| 44 | + { |
| 45 | + if (color[i] != -1 && color[i] != 1 - color[curr]) |
| 46 | + return false; |
| 47 | + else if (color[i] == -1) |
| 48 | + { |
| 49 | + color[i] = 1 - color[curr]; |
| 50 | + pending.push(i); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return true; |
| 55 | + } |
| 56 | + |
| 57 | + bool isBipartite(vector<vector<int>> &graph) |
| 58 | + { |
| 59 | + int n = graph.size(); |
| 60 | + vector<int> color(n, -1); |
| 61 | + |
| 62 | + for (int i = 0; i < n; ++i) |
| 63 | + { |
| 64 | + if (color[i] == -1) |
| 65 | + { |
| 66 | + if (!bfs(i, graph, color)) |
| 67 | + return false; |
| 68 | + }; |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | +}; |
0 commit comments