⼆维矩阵求最⼤连通区域⾯积(python)
2020校招远景的编程题,⼆维01矩阵,横竖算相连,最⼤的连通区域。
思路:⽤⼀个visited列表保存已经过的点,对没的点,如果是1,⽤递归⽅式按上下左右四个⽅向可以连在⼀起的点,存⼊⼀个列表,不断⽐较这个列表长度和之前保存的最⼤值来更新最⼤区域⾯积。 import sys
M,N = list(map(int,adline().strip().split(",")))
mat = []
for _ in range(M):
line = list(map(int,adline().strip().split(",")))
mat.append(line)
def go(i,j,f):
black = []
if 1 in f:
if j>0 and mat[i][j-1] == 1 and [i,j-1] not in visited:
black.append([i,j-1])
visited.append([i,j-1])
利路
防水接头
倒立摆if 2 in f:
if i>0 and mat[i-1][j] == 1 and [i-1,j] not in visited:
black.append([i-1,j])
visited.append([i-1,j])
if 3 in f:
多媒体调度台if j<N-1 and mat[i][j+1] == 1 and [i,j+1] not in visited:连通区域
black.append([i,j+1])
visited.append([i,j+1])
网络滤波器
if 4 in f:
v
if i<M-1 and mat[i+1][j] == 1 and [i+1,j] not in visited:
black.append([i+1,j])
visited.append([i+1,j])
return black
visited = []
res = 0
for i in range(M):
for j in range(N):
if mat[i][j] == 1 and [i,j] not in visited:
visited.append([i,j])
s = go(i,j,[3,4])
if len(s)>res:
res = len(s)+1
print(res)