There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Example 1:
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
Input: graph = [[1,3],[0,2],[1,3],[0,2]]
Output: true
Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
implSolution{#[allow(dead_code)]pubfnis_bipartite(graph:Vec<Vec<i32>>)->bool{letmutgraph=graph;letn=graph.len();letmutcolor_vec:Vec<usize>=vec![0;n];foriin0..n{ifcolor_vec[i]==0&&!Self::traverse(i,1,&mutcolor_vec,&mutgraph){returnfalse;}}true}#[allow(dead_code)]fntraverse(v:usize,color:usize,color_vec:&mutVec<usize>,graph:&mutVec<Vec<i32>>,)->bool{color_vec[v]=color;forningraph[v].clone(){ifcolor_vec[nasusize]==0{// This node hasn't been coloredif!Self::traverse(nasusize,3-color,color_vec,graph){returnfalse;}}elseifcolor_vec[nasusize]==color{// The color is the samereturnfalse;}}true}}
implSolution{#[allow(dead_code)]pubfnis_bipartite(graph:Vec<Vec<i32>>)->bool{letn=graph.len();letmutdisjoint_set:Vec<usize>=vec![0;n];// Initialize the disjoint setforiin0..n{disjoint_set[i]=i;}// Traverse the graphforiin0..n{ifgraph[i].is_empty(){continue;}letfirst=graph[i][0]asusize;forvin&graph[i]{letv=*vasusize;leti_p=Self::find(i,&mutdisjoint_set);letv_p=Self::find(v,&mutdisjoint_set);ifi_p==v_p{returnfalse;}// Otherwise, union the nodeSelf::union(first,v,&mutdisjoint_set);}}true}#[allow(dead_code)]fnfind(x:usize,d_set:&mutVec<usize>)->usize{ifd_set[x]!=x{d_set[x]=Self::find(d_set[x],d_set);}d_set[x]}#[allow(dead_code)]fnunion(x:usize,y:usize,d_set:&mutVec<usize>){letp_x=Self::find(x,d_set);letp_y=Self::find(y,d_set);d_set[p_x]=p_y;}}