二维矩阵求最大连通区域面积(python)

⼆维矩阵求最⼤连通区域⾯积(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)

本文发布于:2024-09-24 08:25:38,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/4/349006.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:保存   列表   防水
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议