Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/785.html
785. Is Graph Bipartite? (Medium)
Given an undirected graph
, return true
if and only if it is bipartite.
Recall that a graph is bipartite if we can split it's 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.
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.
Example 1: Input: [[1,3], [0,2], [1,3], [0,2]] Output: true Explanation: The graph looks like this: 0----1 | | | | 3----2 We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2: Input: [[1,2,3], [0,2], [0,1,3], [0,2]] Output: false Explanation: The graph looks like this: 0----1 | \ | | \ | 3----2 We cannot find a way to divide the set of nodes into two independent subsets.
Note:
graph
will have length in range[1, 100]
.graph[i]
will contain integers in range[0, graph.length - 1]
.graph[i]
will not containi
or duplicate values.- The graph is undirected: if any element
j
is ingraph[i]
, theni
will be ingraph[j]
.
Related Topics:
Depth-first Search, Breadth-first Search, Graph
Solution 1. DFS
// OJ: https://leetcode.com/problems/is-graph-bipartite/
// Time: O(V + E)
// Space: O(V + E)
class Solution {
bool dfs(vector<vector<int>> &G, vector<int> &id, int u, int prev = 1) {
if (id[u]) return id[u] != prev;
id[u] = -prev;
for (int v : G[u]) {
if (!dfs(G, id, v, id[u])) return false;
}
return true;
}
public:
bool isBipartite(vector<vector<int>>& G) {
vector<int> id(G.size());
for (int i = 0; i < G.size(); ++i) {
if (id[i]) continue;
if (!dfs(G, id, i)) return false;
}
return true;
}
};
Solution 2. BFS
// OJ: https://leetcode.com/problems/is-graph-bipartite/
// Time: O(V + E)
// Space: O(V + E)
class Solution {
public:
bool isBipartite(vector<vector<int>>& G) {
vector<int> id(G.size());
queue<int> q;
for (int i = 0; i < G.size(); ++i) {
if (id[i]) continue;
q.push(i);
id[i] = 1;
while (q.size()) {
int u = q.front();
q.pop();
for (int v : G[u]) {
if (id[v]) {
if (id[v] != -id[u]) return false;
continue;
}
id[v] = -id[u];
q.push(v);
}
}
}
return true;
}
};
-
class Solution { public boolean isBipartite(int[][] graph) { int nodes = graph.length; int[] colors = new int[nodes]; Arrays.fill(colors, -1); for (int i = 0; i < nodes; i++) { if (colors[i] == -1) { colors[i] = 0; Stack<Integer> stack = new Stack<Integer>(); stack.push(i); while (!stack.isEmpty()) { int start = stack.pop(); int color = colors[start]; int[] ends = graph[start]; for (int end : ends) { if (colors[end] == -1) { colors[end] = 1 - color; stack.push(end); } else if (colors[start] == colors[end]) return false; } } } } return true; } } ############ class Solution { private int[] color; private int[][] g; public boolean isBipartite(int[][] graph) { int n = graph.length; color = new int[n]; g = graph; for (int i = 0; i < n; ++i) { if (color[i] == 0 && !dfs(i, 1)) { return false; } } return true; } private boolean dfs(int u, int c) { color[u] = c; for (int v : g[u]) { if (color[v] == 0) { if (!dfs(v, 3 - c)) { return false; } } else if (color[v] == c) { return false; } } return true; } }
-
// OJ: https://leetcode.com/problems/is-graph-bipartite/ // Time: O(V + E) // Space: O(V + E) class Solution { public: bool isBipartite(vector<vector<int>>& G) { int N = G.size(); vector<int> id(N); // 0 unseen, 1 and -1 are different colors function<bool(int, int)> dfs = [&](int u, int color) { if (id[u]) return id[u] == color; id[u] = color; for (int v : G[u]) { if (!dfs(v, -color)) return false; } return true; }; for (int i = 0; i < N; ++i) { if (!id[i] && !dfs(i, 1)) return false; } return true; } };
-
class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: def dfs(u, c): color[u] = c for v in graph[u]: if not color[v]: if not dfs(v, 3 - c): return False elif color[v] == c: return False return True n = len(graph) color = [0] * n for i in range(n): if not color[i] and not dfs(i, 1): return False return True ############ class Solution(object): def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: bool """ visited = [0] * len(graph)# 0-not visited; 1-blue; 2-red; for i in range(len(graph)): if graph[i] and visited[i] == 0: visited[i] = 1 q = collections.deque() q.append(i) while q: v = q.popleft()#every point for e in graph[v]:#every edge if visited[e] != 0: if visited[e] == visited[v]: return False else: visited[e] = 3 - visited[v] q.append(e) return True
-
func isBipartite(graph [][]int) bool { n := len(graph) color := make([]int, n) var dfs func(u, c int) bool dfs = func(u, c int) bool { color[u] = c for _, v := range graph[u] { if color[v] == 0 { if !dfs(v, 3-c) { return false } } else if color[v] == c { return false } } return true } for i := range graph { if color[i] == 0 && !dfs(i, 1) { return false } } return true }
-
function isBipartite(graph: number[][]): boolean { const n = graph.length; let valid = true; let colors = new Array(n).fill(0); function dfs(idx: number, color: number, graph: number[][]) { colors[idx] = color; const nextColor = 3 - color; for (let j of graph[idx]) { if (!colors[j]) { dfs(j, nextColor, graph); if (!valid) return; } else if (colors[j] != nextColor) { valid = false; return; } } } for (let i = 0; i < n && valid; i++) { if (!colors[i]) { dfs(i, 1, graph); } } return valid; }