Leetcode Leetcode 547. Number of Provinces

Topic:

There are n cities, some of which are connected to each other, and some are not connected. If city a and city b are directly connected, and city b is directly connected to city c, then city a and city c are indirectly connected.
A province is a group of directly or indirectly connected cities. The group does not contain other unconnected cities.
Give you an nxn matrix isConnected, where isConnected[i][j] = 1 means that the ith city and the jth city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.
Returns the number of provinces in the matrix.

Example_1:
Insert picture description here

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

Example_2:
Insert picture description here

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

Solution:

Here I am directly applying the template. The
boss said that the template connection is great.
Applying the template can solve many problems related to the collection.

To be more specific,
first create a node according to the index and use the index as the node value, and
then process the relationship between
the nodes. The so-called province in this question
is how many sets can be formed.
At the beginning, each node can be regarded as a set
and each time a node is merged, one is reduced. Collection
Finally, the relationship between each node is added. After the merger is completed,
the value of res is the value of the collection, that is, the number of provinces.
In fact, it is relatively simple after mastering the template.

Answer:
Operational efficiency is acceptable

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112424131