二进制矩阵环形岛屿的检测与填充问题技术求助
问题定义
在二进制矩阵M中,**环形岛屿(cyclic island)**是指由1组成的可自我环绕的区域(允许水平、垂直及对角线方向连接)。
任务要求
给定矩阵M,允许的邻接方向为:
directions = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]
需完成以下任务:
- 返回矩阵M中所有的环形岛屿;
- 若存在环形岛屿,将其内部区域设为1,转换为普通岛屿后返回结果;
- 若无环形岛屿则返回原矩阵M。
示例
矩阵M:
M = [[0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0]]
包含3个环形岛屿,示例定义如下:
a = [[0, 2], [1, 1], [1, 3], [2, 1], [2, 2], [2, 3]] b = [[2, 3], [3, 2], [3, 4], [4, 3]] c = [[3, 4], [3, 5], [4, 3], [4, 6], [5, 2], [5, 7], [6, 3], [6, 6], [7, 4], [7, 5]]
填充环形岛屿内部后的输出矩阵:
Output = [[0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0]]
当前进展与困惑
已知需使用DFS算法查找环,但仅能实现每个索引的邻接节点查找,无法建立关联以识别环形岛屿。已编写邻接节点查找代码:
M = [ [0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0]] indices = [] for i in range(len(M)): for j in range(len(M[0])): if M[i][j] == 1: indices.append([i,j]) directions = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)] neighbors = {} while indices: init = indices.pop() current_circle = [init] tracker = [init] while current_circle: x, y = current_circle.pop() neighbors[(x,y)] = [] ctr = 0 for (i, j) in directions: xi, yj = x+i, y+j if [xi, yj] in indices: current_circle.append([xi, yj]) tracker.append([xi, yj]) indices.remove([xi, yj]) neighbors[(x,y)].append([xi, yj]) elif [xi, yj] in tracker: neighbors[(x,y)].append([xi, yj]) neighbors
后续步骤存在困惑,恳请技术帮助。
内容的提问来源于stack exchange,提问作者Semzem
相关产品推荐
相关产品推荐

