File tree Expand file tree Collapse file tree 3 files changed +66
-0
lines changed Expand file tree Collapse file tree 3 files changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } M
3
+ * @return {number }
4
+ */
5
+
6
+ var findCircleNum = function ( M ) {
7
+ function find ( n ) {
8
+ if ( roots [ n ] === n ) return n
9
+ roots [ n ] = find ( roots [ n ] )
10
+ return roots [ n ]
11
+ }
12
+ const roots = Array . from ( M , ( _ , i ) => i )
13
+ for ( let i = 0 , len = M . length ; i < len ; i ++ ) {
14
+ for ( let j = 0 , leng = M [ i ] . length ; j < leng ; j ++ ) {
15
+ if ( ! M [ i ] [ j ] ) continue
16
+ const ri = find ( i )
17
+ const rj = find ( j )
18
+ roots [ ri ] = roots [ rj ] = Math . min ( ri , rj )
19
+ }
20
+ }
21
+ for ( let i = 0 ; i < M . length ; i ++ ) {
22
+ roots [ i ] = find ( i )
23
+ }
24
+
25
+ const set = new Set ( )
26
+ for ( const item of roots ) {
27
+ set . add ( item )
28
+ }
29
+ return set . size
30
+ } ;
Original file line number Diff line number Diff line change
1
+ // https://www.youtube.com/watch?v=TKHIC6muurM
2
+ /**
3
+ * @param {number[][] } M
4
+ * @return {number }
5
+ */
6
+
7
+ var findCircleNum = function ( M ) {
8
+ function dfs ( person ) {
9
+ for ( let i = 0 ; i < M [ person ] . length ; i ++ ) {
10
+ if ( M [ person ] [ i ] && ! seen . has ( i ) ) {
11
+ seen . add ( i )
12
+ dfs ( i )
13
+ }
14
+ }
15
+ }
16
+ const seen = new Set ( )
17
+ let count = 0
18
+ for ( let i = 0 ; i < M . length ; i ++ ) {
19
+ if ( seen . has ( i ) ) continue
20
+ seen . add ( i )
21
+ ++ count
22
+ dfs ( i )
23
+ }
24
+ return count
25
+ } ;
26
+
27
+ if ( process . env . LZS ) {
28
+ console . log (
29
+ findCircleNum (
30
+ [ [ 1 , 1 , 0 ] ,
31
+ [ 1 , 1 , 1 ] ,
32
+ [ 0 , 1 , 1 ] ]
33
+ )
34
+ )
35
+ }
Original file line number Diff line number Diff line change 103
103
- [ 448 Find All Numbers Disappeared in an Array] ( ./448 )
104
104
- [ 495 Teemo Attacking] ( ./495 )
105
105
- [ 532 K-diff Pairs in an Array] ( ./532 )
106
+ - [ 547 Friend Circles] ( ./547 )
106
107
- [ 560 Subarray Sum Equals K] ( ./560 )
107
108
- [ 561 Array Partition I] ( ./561 )
108
109
- [ 565] ( ./565 )
You can’t perform that action at this time.
0 commit comments