File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 210210520|[ Detect Capital] ( ./0520-detect-capital.js ) |Easy|
211211541|[ Reverse String II] ( ./0541-reverse-string-ii.js ) |Easy|
212212542|[ 01 Matrix] ( ./0542-01-matrix.js ) |Medium|
213+ 547|[ Number of Provinces] ( ./0547-number-of-provinces.js ) |Medium|
213214551|[ Student Attendance Record I] ( ./0551-student-attendance-record-i.js ) |Easy|
214215557|[ Reverse Words in a String III] ( ./0557-reverse-words-in-a-string-iii.js ) |Easy|
215216563|[ 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