785. Is Graph Bipartite?
Given an undirected graph, returntrueif 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 jfor which the edge between nodes iand jexists. Each node is an integer between 0and 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:
graphwill have length in range[1, 100].graph[i]will contain integers in range[0, graph.length - 1].graph[i]will not containior duplicate values.The graph is undirected: if any element
jis ingraph[i], theniwill be ingraph[j].
Thoughts:
DFS: color each node:
for each node, first check if it has been colored, if is, return current color value == color to be added
color the node
try color all of its neightbor with different value, if failed, returned false; else return true
Code: BFS T:(V+E); S: O(E): ( For a directed graph, the sum of the sizes of the adjacency lists of all the nodes is E (total number of edges). So, the complexity of DFS is O(V) + O(E) = O(V + E); for an undirected graph, each edge will appear twice. Once in the adjacency list of either end of the edge. So, the overall complexity will be O(V) + O (2E) ~ O(V + E).)
Code: BFS T:(V+E); S:O(V)
Last updated
Was this helpful?