## 题目描述：

LeetCode 547. Friend Circles

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.

## 题目大意：

1. N的范围[1, 200]
2. M[i][i] = 1
3. 如果M[i][j] = 1，那么M[j][i] = 1

## Python代码：

``````class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
N = len(M)
f = range(N)

def find(x):
while f[x] != x: x = f[x]
return x

for x in range(N):
for y in range(x + 1, N):
if M[x][y]: f[find(x)] = find(y)
return sum(f[x] == x for x in range(N))
``````

FloodFill 搜索 + 计数

## Python代码（DFS）：

``````class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
cnt, N = 0, len(M)
vset = set()
def dfs(n):
for x in range(N):
if M[n][x] and x not in vset:
vset.add(x)
dfs(x)
for x in range(N):
if x not in vset:
cnt += 1
dfs(x)
return cnt
``````

## Python代码（BFS）：

``````class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
cnt, N = 0, len(M)
vset = set()
def bfs(n):
q = [n]
while q:
n = q.pop(0)
for x in range(N):
if M[n][x] and x not in vset:
vset.add(x)
q.append(x)
for x in range(N):
if x not in vset:
cnt += 1
bfs(x)
return cnt
``````

Floyd-Warshall算法参阅：

https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm

## Python代码：

``````class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
N = len(M)
for k in range(N):
for i in range(N):
for j in range(N):
M[i][j] = M[i][j] or (M[i][k] and M[k][j])
cnt = 0
vset = set()
for x in range(N):
if x not in vset:
cnt += 1
for y in range(x + 1, N):
if M[x][y]: vset.add(y)
return cnt
``````

Pingbacks已关闭。