785. Is Graph Bipartite?
Given an undirected graph
, returntrue
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.
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]
.
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?