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: trueExplanation: The graph looks like this:0----1| || |3----2We 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: falseExplanation: The graph looks like this:0----1| \ || \ |3----2We cannot find a way to divide the set of nodes into two independent subsets.
M1: BFS
time: O(V + E), space: O(V)
class Solution { public boolean isBipartite(int[][] graph) { int[] visited = new int[graph.length]; for(int i = 0; i < graph.length; i++) { if(!BFS(graph, i, visited)) { return false; } } return true; } private boolean BFS(int[][] graph, int node, int[] visited) { if(visited[node] != 0) { return true; } Queueq = new LinkedList<>(); q.offer(node); visited[node] = 1; while(!q.isEmpty()) { int cur = q.poll(); int curColor = visited[cur]; int neiColor = -curColor; for(int nei : graph[cur]) { if(visited[nei] == 0) { visited[nei] = neiColor; q.offer(nei); } else if(visited[nei] != neiColor) { return false; } } } return true; }}
M2: DFS
Graph Coloring (by DFS/BFS): color a node as red, and then color all its neighbors as blue recursively. if there's any conflict, return false.
class Solution { int[] colors; public boolean isBipartite(int[][] graph) { int n = graph.length; colors = new int[n]; for(int i = 0; i < n; i++) { if(colors[i] == 0 && !dfs(graph, i, 1)) return false; } return true; } private boolean dfs(int[][] graph, int node, int color) { if(colors[node] != 0) return colors[node] == color ? true: false; else { colors[node] = color; for(int j : graph[node]) { if(!dfs(graph, j, -color)) return false; } } return true; }}