1. 朋友圈
班上有 N 名學生。其中有些人是朋友,有些則不是。他們的友誼具有是傳遞性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那麼我們可以認爲 A 也是 C 的朋友。所謂的朋友圈,是指所有朋友的集合。
給定一個 N * N 的矩陣 M,表示班級中學生之間的朋友關係。如果M[i][j] = 1,表示已知第 i 個和 j 個學生互爲朋友關係,否則爲不知道。你必須輸出所有學生中的已知的朋友圈總數。
示例1
輸入:
[[1,1,0],
[1,1,0],
[0,0,1]]
輸出: 2
說明:已知學生0和學生1互爲朋友,他們在一個朋友圈。
第2個學生自己在一個朋友圈。所以返回2。
示例2
輸入:
[[1,1,0],
[1,1,1],
[0,1,1]]
輸出: 1
說明:已知學生0和學生1互爲朋友,學生1和學生2互爲朋友,所以學生0和學生2也是朋友,所以他們三個在一個朋友圈,返回1。
注意:
- N 在[1,200]的範圍內。
- 對於所有學生,有M[i][i] = 1。
- 如果有M[i][j] = 1,則有M[j][i] = 1。
class Solution(object):
def __init__(self):
self.cnt = 0
self.arr = []
self.M = []
self.n = 0
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
self.M = M
self.n = len(M)
self.arr = [False for j in range(self.n)]
for i in range(self.n):
if self.arr[i] == False:
self.cnt += 1
self.arr[i] = True
for j in range(i+1,self.n):
if self.M[i][j] == 1 and self.arr[j] == False:
self.findFriends(j)
return self.cnt
def findFriends(self,index):
self.arr[index] = True
for j in range(self.n):
if self.M[index][j] == 1 and self.arr[j] == False :
self.findFriends(j)
2. 島嶼的最大面積
給定一個包含了一些 0 和 1的非空二維數組 grid , 一個 島嶼 是由四個方向 (水平或垂直) 的 1 (代表土地) 構成的組合。你可以假設二維矩陣的四個邊緣都被水包圍着。
找到給定的二維數組中最大的島嶼面積。(如果沒有島嶼,則返回面積爲0。)
示例2
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
- 對於上面這個給定矩陣應返回 6。注意答案不應該是11,因爲島嶼只能包含水平或垂直的四個方向的‘1’。
示例2
[[0,0,0,0,0,0,0,0]]
- 對於上面這個給定的矩陣, 返回 0。
注意: 給定的矩陣grid 的長度和寬度都不超過 50。
class Solution(object):
def __init__(self):
self.grid = []
self.m = 0
self.n = 0
self.v = []
self.cnt = 0
self.foo = 0
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
self.grid = grid
self.m = len(grid)
self.n = len(grid[0])
for i in range(self.m):
self.v.append([0 for j in range(self.n)])
for i in range(self.m):
for j in range(self.n):
if self.grid[i][j] == 1 and self.v[i][j] == 0:
self.findOuter(i,j)
self.cnt = max(self.foo,self.cnt)
self.foo = 0
return self.cnt
def findOuter(self,i,j):
self.foo += 1
self.v[i][j] = 1
if i-1 >= 0 and self.grid[i-1][j] == 1 and self.v[i-1][j] == 0:
self.findOuter(i-1,j)
if i+1 < self.m and self.grid[i+1][j] == 1 and self.v[i+1][j] == 0:
self.findOuter(i+1,j)
if j-1 >= 0 and self.grid[i][j-1] == 1 and self.v[i][j-1] == 0:
self.findOuter(i,j-1)
if j+1 < self.n and self.grid[i][j+1] == 1 and self.v[i][j+1] == 0:
self.findOuter(i,j+1)