【问题标题】:List index error for finding largest cluster in 2-D array在二维数组中查找最大簇的列表索引错误
【发布时间】:2021-05-17 15:42:15
【问题描述】:

我一直在尝试使用朋友发给我的这段代码,以帮助找到给定数组中最大的连通序列 1。

首先,我对网格、行和列的数据进行硬编码,如您在提供的代码中所见。网格将始终有 3 列,但行的长度会有所不同,因此,我的列表重复出现“索引超出范围”错误的问题。

我做错了什么,我该如何解决这个问题,因为我自己想不出答案。

# Python3 program
row = 6
col = 3

vis = [[0 for i in range(col + 1)] for j in range(row + 1)] 
id = 0
diameter = 0
length = 0

# Keeps a track of directions
# that is up, down, left, right
dx = [ -1, 1, 0, 0 ]
dy = [ 0, 0, -1, 1 ]

# Function to perform the dfs traversal
def dfs(a, b, lis, x, y):
    
    global id, length, diameter
    
    # Mark the current node as visited
    vis[a][b] = id

    # Increment length from this node
    length += 1

    # Update the diameter length
    if (length > diameter):
        x = a
        y = b
        diameter = length
    
    for j in range(4):

        # Move to next cell in x-direction
        cx = a + dx[j]

        # Move to next cell in y-direction
        cy = b + dy[j]

        # Check if cell is invalid
        # then continue
        if (cx < 0 or cy < 0 or
            cx >= row or cy >= col or
            lis[cx][cy] == 0 or vis[cx][cy]):
            continue
    
        # Perform DFS on new cell
        dfs(cx, cy, lis, x, y)
    
    vis[a][b] = 0

    # Decrement the length
    length -= 1
    
    return x, y

# Function to find the maximum length of
# connected 1s in the given grid
def findMaximumLength(lis):
    
    global id, length, diameter
    
    x = 0
    y = 0

    # Increment the id
    id += 1
    
    length = 0
    diameter = 0

    # Traverse the grid[]
    for i in range(row):
        for j in range(col):
            if (lis[i][j] != 0):

                # Find start point of
                # start dfs call
                x, y = dfs(i, j, lis, x, y)
                i = row
                break

    id += 1
    length = 0
    diameter = 0

    # DFS Traversal from cell (x, y)
    x, y = dfs(x, y, lis, x, y)

    # Print the maximum length
    print(diameter)

# Driver Code
if __name__=="__main__":
    
    # Given grid[][]
    grid = [ [ 1, 1, 0, 1, 1, 1 ],
            [ 1, 1, 1, 0, 0, 0 ],
            [ 1, 1, 1, 1, 1, 1 ] ]

    # Function Call
    findMaximumLength(grid)


任何帮助将不胜感激。

【问题讨论】:

  • 在递归函数中使用全局变量通常是错误的。建议您在使用时检查这些变量是否具有所需的值。

标签: python arrays list matrix gaps-and-islands


【解决方案1】:

所以经过一番搜索后,我找到了一段代码,可以用最少的编码获得我想要的结果:

Max area of an island of 1's in a 2D array

【讨论】:

    【解决方案2】:

    您的朋友硬编码了 rowcol 变量。 rowcol 变量应该与您的网格形状相匹配。你有 3x6,参数是 6x3。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2019-07-24
      • 2017-04-03
      • 2019-07-05
      相关资源
      最近更新 更多