547.friend-circles-en
Problem
https://leetcode.com/problems/friend-circles/
Problem Description
Solution
We can view a given matrix as Adjacency Matrix of a graph. In this case, this problem become to find number of connected components in a undirected graph.
For example, how to transfer Adjacency Matrix into a graph problem. As below pic:
Connected components in a graph problem usually can be solved using DFS, BFS, Union-Find.
Below we will explain details on each approach.
Approach #1. DFS
Do DFS starting from every node, use
visited
array to mark visited node.For each node DFS, visit all its directly connected nodes.
For each node DFS, DFS search will search all connected nodes, thus we count one DFS as one connected component.
as below pic show DFS traverse process:
Complexity Analysis
Time Complexity:
O(n*n) - n is the number of students, traverse n*n matrix
Space Complexity:
O(n) - visited array of size n
Approach #2. BFS (Level traverse)
Start from one node, visit all its directly connected nodes, or visit all nodes in the same level.
Use
visited
array to mark already visited nodes.Increment count when start with a new node.
as below pic show BFS (Level traverse) traverse process:
Complexity Analysis
Time Complexity:
O(n*n) - n is the number of students, traverse n*n matrix
Space Complexity:
O(n) - queue and visited array of size n
Approach #3. Union-Find
Determine number of connected components, Union Find is good algorithm to use.
Use parent
array, for every node, all its directly connected nodes will be union
, so that two connected nodes have the same parent. After traversal all nodes, we just need to calculate the number of different values in parent
array.
For each union, total count minus 1, after traversal and union all connected nodes, simply return counts.
Here use weighted-union-find to reduce union
and find
methods operation time.
To know more details and implementations, see further reading lists.
as below Union-Find approach process:
Note: here using weighted-union-find to avoid Union and Find take
O(n)
in the worst case.
Complexity Analysis
Time Complexity:
O(n*n*log(n) - traverse n*n matrix, weighted-union-find, union and find takes log(n) time complexity.
Space Complexity:
O(n) - parent and rank array of size n
Key Points
Transform Adjacency matrix into Graph
Notice that it actually is to find number of connected components problem.
Connected components problem approaches (DFS, BFS, Union-Find).
Code (Java
)
Java
)Java code - DFS
Java code - BFS
Java code - Union-Find
References (Further reading)
Similar Problems
Last updated