##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/547.html

# 547. Friend Circles (Medium)

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2.


Example 2:

Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.


Note:

1. N is in range [1,200].
2. M[i][i] = 1 for all students.
3. If M[i][j] = 1, then M[j][i] = 1.

Companies:

Related Topics:
Depth-first Search, Union Find

Similar Questions:

## Solution 1. Union Find

// OJ: https://leetcode.com/problems/friend-circles/
// Time: O(N^2 * a(N)), where a is the inverse function of Ackermann function. O(a(N)) is faster than O(log(N)).
// Space: O(N)
class UnionFind {
private:
vector<int> rank;
vector<int> id;
int count;
int find (int i) {
if (id[i] == i) return i;
return id[i] = find(id[i]);
}
public:
UnionFind(int n) : rank(n, 0), id(n), count(n) {
for (int i = 0; i < n; ++i) id[i] = i;
}
void connect(int i, int j) {
int p = find(i), q = find(j);
if (p == q) return;
if (rank[p] > rank[q]) id[p] = q;
else {
id[q] = p;
if (rank[p] == rank[q]) rank[p]++;
}
--count;
}
int getCount() { return count; }
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& M) {
int N = M.size();
UnionFind uf(N);
for (int i = 0; i < N; ++i)
for (int j = i + 1; j < N; ++j)
if (M[i][j]) uf.connect(i, j);
return uf.getCount();
}
};


## Solution 2. DFS

// OJ: https://leetcode.com/problems/friend-circles
// Time: O(N^2)
// Space: O(N)
class Solution {
private:
void dfs(vector<vector<int>>& M, int i, vector<bool> &visited) {
visited[i] = true;
for (int j = i + 1; j < M.size(); ++j) {
if (!M[i][j] || visited[j]) continue;
dfs(M, j, visited);
}
}
public:
int findCircleNum(vector<vector<int>>& M) {
vector<bool> visited(M.size(), false);
int cnt = 0;
for (int i = 0; i < M.size(); ++i) {
if (visited[i]) continue;
dfs(M, i, visited);
++cnt;
}
return cnt;
}
};

• class Solution {
public int findCircleNum(int[][] M) {
Map<Integer, Set<Integer>> friendsMap = new HashMap<Integer, Set<Integer>>();
int studentsCount = M.length;
for (int i = 0; i < studentsCount; i++) {
Set<Integer> set = new HashSet<Integer>();
friendsMap.put(i, set);
}
for (int i = 0; i < studentsCount; i++) {
for (int j = i + 1; j < studentsCount; j++) {
if (M[i][j] == 1) {
Set<Integer> set1 = friendsMap.getOrDefault(i, new HashSet<Integer>());
Set<Integer> set2 = friendsMap.getOrDefault(j, new HashSet<Integer>());
Set<Integer> unionSet = new HashSet<Integer>(set1);
for (int student : unionSet)
friendsMap.put(student, unionSet);
}
}
}
int circles = 0;
Set<Integer> totalSet = new HashSet<Integer>();
for (int i = 0; i < studentsCount; i++) {
if (!totalSet.contains(i)) {
Set<Integer> set = friendsMap.getOrDefault(i, new HashSet<Integer>());
circles++;
}
}
return circles;
}
}

############

class Solution {
private int[][] isConnected;
private boolean[] vis;
private int n;

public int findCircleNum(int[][] isConnected) {
n = isConnected.length;
vis = new boolean[n];
this.isConnected = isConnected;
int ans = 0;
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
dfs(i);
++ans;
}
}
return ans;
}

private void dfs(int i) {
vis[i] = true;
for (int j = 0; j < n; ++j) {
if (!vis[j] && isConnected[i][j] == 1) {
dfs(j);
}
}
}
}

• // OJ: https://leetcode.com/problems/friend-circles
// Time: O(N^2)
// Space: O(N)
class Solution {
private:
void dfs(vector<vector<int>>& M, int i, vector<bool> &visited) {
visited[i] = true;
for (int j = i + 1; j < M.size(); ++j) {
if (!M[i][j] || visited[j]) continue;
dfs(M, j, visited);
}
}
public:
int findCircleNum(vector<vector<int>>& M) {
vector<bool> visited(M.size(), false);
int cnt = 0;
for (int i = 0; i < M.size(); ++i) {
if (visited[i]) continue;
dfs(M, i, visited);
++cnt;
}
return cnt;
}
};

• class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def dfs(i):
vis[i] = True
for j in range(n):
if not vis[j] and isConnected[i][j]:
dfs(j)

n = len(isConnected)
vis = [False] * n
ans = 0
for i in range(n):
if not vis[i]:
dfs(i)
ans += 1
return ans

############

class UnionFind(object):
def __init__(self, n):
self.dad = [i for i in range(n)]
self.rank = [0 for i in range(n)]
self.count = n

def find(self, x):

def union(self, x, y):
rank = self.rank
x, y = map(self.find, [x, y])
if x == y:
return False
if rank[x] > rank[y]:
else:
if rank[x] == rank[y]:
rank[y] += 1
self.count -= 1
return True

def getCount(self):
return self.count

class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
uf = UnionFind(len(M))
ans = 0
for i in range(len(M)):
for j in range(len(M)):
if M[i][j] == 1:
uf.union(i, j)
return uf.getCount()


• func findCircleNum(isConnected [][]int) int {
n := len(isConnected)
vis := make([]bool, n)
var dfs func(i int)
dfs = func(i int) {
vis[i] = true
for j := 0; j < n; j++ {
if !vis[j] && isConnected[i][j] == 1 {
dfs(j)
}
}
}
ans := 0
for i := 0; i < n; i++ {
if !vis[i] {
dfs(i)
ans++
}
}
return ans
}

• impl Solution {
fn dfs(is_connected: &mut Vec<Vec<i32>>, vis: &mut Vec<bool>, i: usize) {
vis[i] = true;
for j in 0..is_connected.len() {
if vis[j] || is_connected[i][j] == 0 {
continue;
}
Self::dfs(is_connected, vis, j);
}
}

pub fn find_circle_num(mut is_connected: Vec<Vec<i32>>) -> i32 {
let n = is_connected.len();
let mut vis = vec![false; n];
let mut res = 0;
for i in 0..n {
if vis[i] {
continue;
}
res += 1;
Self::dfs(&mut is_connected, &mut vis, i);
}
res
}
}


• function findCircleNum(isConnected: number[][]): number {
const n = isConnected.length;
const vis: boolean[] = new Array(n).fill(false);
const dfs = (i: number) => {
vis[i] = true;
for (let j = 0; j < n; ++j) {
if (!vis[j] && isConnected[i][j]) {
dfs(j);
}
}
};
let ans = 0;
for (let i = 0; i < n; ++i) {
if (!vis[i]) {
dfs(i);
++ans;
}
}
return ans;
}