File tree 2 files changed +45
-0
lines changed
2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 210
210
520|[ Detect Capital] ( ./0520-detect-capital.js ) |Easy|
211
211
541|[ Reverse String II] ( ./0541-reverse-string-ii.js ) |Easy|
212
212
542|[ 01 Matrix] ( ./0542-01-matrix.js ) |Medium|
213
+ 547|[ Number of Provinces] ( ./0547-number-of-provinces.js ) |Medium|
213
214
551|[ Student Attendance Record I] ( ./0551-student-attendance-record-i.js ) |Easy|
214
215
557|[ Reverse Words in a String III] ( ./0557-reverse-words-in-a-string-iii.js ) |Easy|
215
216
563|[ Binary Tree Tilt] ( ./0563-binary-tree-tilt.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 547. Number of Provinces
3
+ * https://leetcode.com/problems/number-of-provinces/
4
+ * Difficulty: Medium
5
+ *
6
+ * There are n cities. Some of them are connected, while some are not. If city a is connected
7
+ * directly with city b, and city b is connected directly with city c, then city a is connected
8
+ * indirectly with city c.
9
+ *
10
+ * A province is a group of directly or indirectly connected cities and no other cities outside
11
+ * of the group.
12
+ *
13
+ * You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the
14
+ * jth city are directly connected, and isConnected[i][j] = 0 otherwise.
15
+
16
+ Return the total number of provinces.
17
+ */
18
+
19
+ /**
20
+ * @param {number[][] } isConnected
21
+ * @return {number }
22
+ */
23
+ var findCircleNum = function ( isConnected ) {
24
+ const seen = new Array ( isConnected . length ) . fill ( 0 ) ;
25
+ let result = 0 ;
26
+
27
+ function dfs ( node ) {
28
+ seen [ node ] = 1 ;
29
+ for ( let i = 0 ; i < isConnected . length ; i ++ ) {
30
+ if ( isConnected [ node ] [ i ] === 1 && ! seen [ i ] ) {
31
+ dfs ( i ) ;
32
+ }
33
+ }
34
+ }
35
+
36
+ for ( let i = 0 ; i < isConnected . length ; i ++ ) {
37
+ if ( ! seen [ i ] ) {
38
+ result ++ ;
39
+ dfs ( i ) ;
40
+ }
41
+ }
42
+
43
+ return result ;
44
+ } ;
You can’t perform that action at this time.
0 commit comments