当前位置:网站首页>Leetcode (547) - number of provinces
Leetcode (547) - number of provinces
2022-07-07 00:44:00 【SmileGuy17】
Leetcode(547)—— Number of provinces
subject
Yes n n n Cities , Some of them are connected to each other , Others are not connected . If the city a a a And the city b b b Direct connection , And the city b b b And the city c c c Direct connection , So the city a a a And the city c c c Indirectly connected .
Province It's a group of directly or indirectly connected cities , There are no other cities in the group that are not connected .
To give you one n × n n \times n n×n Matrix i s C o n n e c t e d isConnected isConnected, among i s C o n n e c t e d [ i ] [ j ] = 1 isConnected[i][j] = 1 isConnected[i][j]=1 It means the first one i i i Two cities and j j j The two cities are directly connected , and i s C o n n e c t e d [ i ] [ j ] = 0 isConnected[i][j] = 0 isConnected[i][j]=0 The two are not directly connected .
Back in the matrix Province The number of .
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
Tips :
- 1 1 1 <= n <= 200 200 200
- n == isConnected.length
- n == isConnected[i].length
- isConnected[i][j] by 1 1 1 or 0 0 0
- isConnected[i][i] == 1 1 1
- isConnected[i][j] == isConnected[j][i]
Answer key
Method 1 :DFS
Ideas
The idea of depth first search is very intuitive . Traverse all cities , For every city , If the city has not been visited , Then start the depth first search from the city , Through the matrix isConnected \textit{isConnected} isConnected Get what cities are directly connected to the city , These cities and the city belong to the same connected component , Then continue the depth first search for these cities , Until all cities of the same connected component are visited , You can get a province . After traversing all the cities , You can get the total number of connected components , That is, the total number of provinces .
Code implementation
Leetcode Official explanation ( recursive ):
class Solution {
public:
void dfs(vector<vector<int>>& isConnected, vector<int>& visited, int cities, int i) {
for (int j = 0; j < cities; j++) {
if (isConnected[i][j] == 1 && !visited[j]) {
visited[j] = 1;
dfs(isConnected, visited, cities, j);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int cities = isConnected.size();
vector<int> visited(cities);
int provinces = 0;
for (int i = 0; i < cities; i++) {
if (!visited[i]) {
dfs(isConnected, visited, cities, i);
provinces++;
}
}
return provinces;
}
};
My own ( iteration ):
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
// The adjacency matrix of an undirected graph is known , Find the number of connected components in the graph
int size = isConnected.size(), ans = 0, city;
stack<int> tmp;
vector<bool> visited(size, false);
for(int n = 0; n < size; n++){
// The city has not been divided into provinces
if(visited[n] == false){
++ans;
tmp.push(n);
while(!tmp.empty()){
city = tmp.top();
tmp.pop();
if(visited[city] == true) continue;
visited[city] = true; // Division of provinces
for(int i = 0; i < size; i++)
if(isConnected[city][i] == 1) tmp.push(i);
}
}
}
return ans;
}
};
Complexity analysis
Time complexity : O ( n 2 ) O(n^2) O(n2), among n n n It's the number of cities . Need to traverse the matrix isConnected \textit{isConnected} isConnected Every element in .
Spatial complexity : O ( n ) O(n) O(n), among n n n It's the number of cities . You need to use an array visited \textit{visited} visited Record whether each city has been visited , The length of the array is n n n, The depth of the recursive call stack will not exceed n n n.
Method 2 :BFS
Ideas
You can also get the total number of provinces by breadth first search . For every city , If the city has not been visited , Then start breadth first search from the city , Until all cities in the same connected component are visited , You can get a province .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int cities = isConnected.size();
vector<int> visited(cities);
int provinces = 0;
queue<int> Q;
for (int i = 0; i < cities; i++) {
if (!visited[i]) {
Q.push(i);
while (!Q.empty()) {
int j = Q.front(); Q.pop();
visited[j] = 1;
for (int k = 0; k < cities; k++) {
if (isConnected[j][k] == 1 && !visited[k]) {
Q.push(k);
}
}
}
provinces++;
}
}
return provinces;
}
};
My own ( Iterative writing ):
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
// The adjacency matrix of an undirected graph is known , Find the number of connected components in the graph
int size = isConnected.size(), ans = 0, city;
queue<int> tmp;
vector<bool> visited(size, false);
for(int n = 0; n < size; n++){
// The city has not been divided into provinces
if(visited[n] == false){
++ans;
tmp.push(n);
while(!tmp.empty()){
city = tmp.front();
tmp.pop();
if(visited[city] == true) continue;
visited[city] = true; // Division of provinces
for(int i = 0; i < size; i++)
if(isConnected[city][i] == 1) tmp.push(i);
}
}
}
return ans;
}
};
Complexity analysis
Time complexity : O ( n 2 ) O(n^2) O(n2), among n n n It's the number of cities . Need to traverse the matrix isConnected \textit{isConnected} isConnected Every element in .
Spatial complexity : O ( n ) O(n) O(n), among n n n It's the number of cities . You need to use an array visited \textit{visited} visited Record whether each city has been visited , The length of the array is n n n, The number of elements in the queue used by breadth first search will not exceed n n n.
Method 3 : Union checking set
Ideas
Another way to calculate the number of connected components is to use union search set . At the beginning , Each city belongs to a different connectivity component . ergodic matrix isConnected \textit{isConnected} isConnected, If there is a connection between two cities , Then they belong to the same connected component , Merge them .
ergodic matrix isConnected \textit{isConnected} isConnected After all the elements of , Calculate the total number of connected components , That is the total number of provinces .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int Find(vector<int>& parent, int index) {
if (parent[index] != index) {
parent[index] = Find(parent, parent[index]);
}
return parent[index];
}
void Union(vector<int>& parent, int index1, int index2) {
parent[Find(parent, index1)] = Find(parent, index2);
}
int findCircleNum(vector<vector<int>>& isConnected) {
int cities = isConnected.size();
vector<int> parent(cities);
for (int i = 0; i < cities; i++) {
parent[i] = i;
}
for (int i = 0; i < cities; i++) {
for (int j = i + 1; j < cities; j++) {
if (isConnected[i][j] == 1) {
Union(parent, i, j);
}
}
}
int provinces = 0;
for (int i = 0; i < cities; i++) {
if (parent[i] == i) {
provinces++;
}
}
return provinces;
}
};
My own :
class Solution {
int Find(vector<int>& citys, int city){
if(citys[city] == city) return city;
else return citys[city] = Find(citys, citys[city]);
}
void Union(vector<int>& citys, int city1, int city2){
citys[Find(citys, city2)] = Find(citys, city1); // Connect the two sets
}
public:
int findCircleNum(vector<vector<int>>& isConnected) {
// The adjacency matrix of an undirected graph is known , Find the number of connected components in the graph
int size = isConnected.size(), ans = 0, city, root1, root2;
vector<int> citys;
// Create and query an array
for(int n = 0; n < size; n++)
citys.push_back(n);
for(int n = 0; n < size; n++){
for(int i = 0; i < size; i++){
if(isConnected[n][i] == 1)
Union(citys, n, i);
}
}
for(int n = 0; n < size; n++)
if(citys[n] == n) ans++;
return ans;
}
};
Complexity analysis
Time complexity : O ( n 2 log n ) O(n^2 \log n) O(n2logn), among n n n It's the number of cities . Need to traverse the matrix isConnected \textit{isConnected} isConnected All elements in , The time complexity is O ( n 2 ) O(n^2) O(n2), If you encounter a connection , You need to do 2 2 2 Find and maximum 1 1 1 The merger , A total of 2 n 2 2n^2 2n2 Find and maximum n 2 n^2 n2 The merger , So the total time complexity is O ( 2 n 2 log n 2 ) = O ( n 2 log n ) O(2n^2 \log n^2)=O(n^2 \log n) O(2n2logn2)=O(n2logn). The join set here uses path compression , However, rank merging is not used , The worst-case time complexity is O ( n 2 log n ) O(n^2 \log n) O(n2logn), The average time complexity is still O ( n 2 α ( n ) ) O(n^2 \alpha (n)) O(n2α(n)), among α \alpha α Is the inverse of the Ackerman function , α ( n ) \alpha (n) α(n) It can be considered a very small constant .
Spatial complexity : O ( n ) O(n) O(n), among n n n It's the number of cities . You need to use an array parent \textit{parent} parent Record the ancestors of the connected components to which each city belongs .
边栏推荐
- File and image comparison tool kaleidoscope latest download
- What is time
- How to use vector_ How to use vector pointer
- The difference between redirectto and navigateto in uniapp
- AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
- String comparison in batch file - string comparison in batch file
- Google, Baidu and Yahoo are general search engines developed by Chinese companies_ Baidu search engine URL
- Leecode brushes questions to record interview questions 17.16 massagist
- Core knowledge of distributed cache
- Everyone is always talking about EQ, so what is EQ?
猜你喜欢
智能运维应用之道,告别企业数字化转型危机
Mujoco Jacobi - inverse motion - sensor
Mujoco finite state machine and trajectory tracking
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis
Hero League | King | cross the line of fire BGM AI score competition sharing
深度学习之线性代数
Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
三维扫描体数据的VTK体绘制程序设计
基于SSM框架的文章管理系统
2022/2/10 summary
随机推荐
Advanced learning of MySQL -- basics -- multi table query -- self join
Business process testing based on functional testing
【软件逆向-自动化】逆向工具大全
Advanced learning of MySQL -- basics -- multi table query -- joint query
Hero League | King | cross the line of fire BGM AI score competition sharing
System activity monitor ISTAT menus 6.61 (1185) Chinese repair
2022 PMP project management examination agile knowledge points (9)
Data sharing of the 835 postgraduate entrance examination of software engineering in Hainan University in 23
Racher integrates LDAP to realize unified account login
Three application characteristics of immersive projection in offline display
What is time
dynamic programming
509 certificat basé sur Go
PXE server configuration
The programmer resigned and was sentenced to 10 months for deleting the code. Jingdong came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
Google, Baidu and Yahoo are general search engines developed by Chinese companies_ Baidu search engine URL
Matlab learning notes
Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
37 page overall planning and construction plan for digital Village revitalization of smart agriculture
Compilation of kickstart file