File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } N
3
+ * @param {number[][] } dislikes
4
+ * @return {boolean }
5
+ */
6
+ const possibleBipartition = function ( N , dislikes ) {
7
+ const graph = [ ]
8
+ for ( let i = 0 ; i <= N ; i ++ ) {
9
+ graph [ i ] = [ ]
10
+ }
11
+ for ( let el of dislikes ) {
12
+ graph [ el [ 0 ] ] . push ( el [ 1 ] )
13
+ graph [ el [ 1 ] ] . push ( el [ 0 ] )
14
+ }
15
+ const color = new Array ( N + 1 ) . fill ( 0 )
16
+ for ( let i = 1 ; i <= N ; i ++ ) {
17
+ if ( color [ i ] == 0 ) {
18
+ color [ i ] = 1 ;
19
+ const q = [ ] ;
20
+ q . push ( i ) ;
21
+ while ( q . length > 0 ) {
22
+ let cur = q . shift ( ) ;
23
+ for ( let j of graph [ cur ] ) {
24
+ if ( color [ j ] == 0 ) {
25
+ color [ j ] = color [ cur ] == 1 ? 2 : 1 ;
26
+ q . push ( j ) ;
27
+ } else {
28
+ if ( color [ j ] == color [ cur ] ) return false ;
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ return true
35
+ } ;
You can’t perform that action at this time.
0 commit comments