Learn Algorithms from LeetCode-120 (0547. Number of Provinces)

Categories: Graph/Union Find, Level: Medium

Chih-Yu Lin

--

Introduction: (Basic + Advanced + Interview Edition)
Learning Algorithms from LeetCode + Interview Success Guide
(Regular price: 3591 NTD, Discounted price until 2023/06/30 23:59)
https://hiskio.com/bundles/eCP23B397?s=tc

(Regular price: 3990 NTD, Valid for a long term)
https://bit.ly/lc2022all

Please help me click on the “SHOW EMBED” below and give it 5 likes~ If you like it, you can also give me a round of applause~
(Liking doesn’t cost anything, thank you for supporting my writing~)

Question:

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

Example 1:

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2

Example 2:

Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3

Constraints:

  • 1 <= n <= 200
  • n == isConnected.length
  • n == isConnected[i].length
  • isConnected[i][j] is 1 or 0.
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

Analysis/Approach:

There are n cities, some of which are directly connected to each other, while others are not. If city a is directly connected to city b, and city b is directly connected to city c, then city a is…

--

--

Chih-Yu Lin

LeetCode、Python、Java、Android;第11屆iT邦幫忙鐵人賽Software Development組優選(從LeetCode學演算法);HiSKIO特約講師;課程優惠: https://bit.ly/lc2022all ;合作請洽: learnwithdesolve@gmail.com