Python中查找最大长度的蛇形序列
假设我们有一个数字网格;我们必须找到一个蛇形序列并返回它。如果有多个蛇形序列,则只返回一个。众所周知,蛇形序列是由网格中相邻数字构成的,因此对于每个数字,其右侧或下方的数字与其值的差值为+1或-1。因此,如果当前值位于网格单元格(a, b)中,则如果该数字为±1,我们可以向右移动(a, b+1),或者如果该数字为±1,则向下移动(a+1, b)。
因此,如果输入如下所示:
10 | 7 | 6 | 3 |
9 | 8 | 7 | 6 |
8 | 4 | 2 | 7 |
2 | 2 | 2 | 8 |
则输出将为6,序列 - 10 (0, 0) 到 9 (1, 0) 到 8 (1, 1) 到 7 (1, 2) 到 6 (1, 3) 到 7 (2, 3) 到 8 (3, 3)
为了解决这个问题,我们将遵循以下步骤:
定义一个函数`get_path()`。这将接收网格、mat、i、j。
path := 新列表
pt := 一个点 [i, j]
将pt插入path的末尾
当grid[i, j]不为0时,执行:
如果 i > 0 且 grid[i, j]-1 等于 grid[i-1, j],则
pt := [i-1, j]
将pt插入path的末尾
i := i - 1
否则,如果 j > 0 且 grid[i, j]-1 等于 grid[i, j-1],则
pt := [i, j-1]
将pt插入path的末尾
j := j - 1
返回path
从主方法中,执行以下操作:
lookup := 创建一个大小为M x N的网格并用0填充
length_max := 0, max_row := 0, max_col := 0
对于范围0到M中的i,执行:
对于范围0到N中的j,执行:
如果i或j不为零,则
如果 (i > 0 且 |grid[i-1, j] - grid[i, j]| 为1),则
lookup[i,j] = lookup[i,j],lookup[i-1,j] + 1 的最大值
如果 length_max < lookup[i,j],则
length_max := lookup[i, j]
max_row := i
max_col := j
如果 (j > 0 且 |grid[i, j-1] - grid[i, j]| 为1),则
如果 length_max < lookup[i][j] 不为零,则
lookup[i,j] = lookup[i,j],lookup[i,j-1] + 1 的最大值
length_max := lookup[i, j]
max_row := i
max_col := j
显示 length_max
path := get_path(lookup, grid, max_row, max_col)
以相反的顺序打印path中的所有元素
示例
让我们看看下面的实现,以便更好地理解;
M = 4 N = 4 def get_path(grid, mat, i, j): path = list() pt = [i, j] path.append(pt) while (grid[i][j] != 0): if (i > 0 and grid[i][j]-1 == grid[i-1][j]): pt = [i-1, j] path.append(pt) i -= 1 elif (j > 0 and grid[i][j]-1 == grid[i][j-1]): pt = [i, j-1] path.append(pt) j -= 1 return path def get_sequence(grid): lookup = [[0 for i in range(N)] for j in range(M)] length_max = 0 max_row = 0 max_col = 0 for i in range(M): for j in range(N): if (i or j): if (i > 0 and abs(grid[i-1][j] - grid[i][j]) == 1): lookup[i][j] = max(lookup[i][j],lookup[i-1][j] + 1) if (length_max < lookup[i][j]): length_max = lookup[i][j] max_row = i max_col = j if (j > 0 and abs(grid[i][j-1] - grid[i][j]) == 1): lookup[i][j] = max(lookup[i][j],lookup[i][j-1] + 1) if (length_max < lookup[i][j]): length_max = lookup[i][j] max_row = i max_col = j print("Maximum length:", length_max) path = get_path(lookup, grid, max_row, max_col) print("Sequence is:") for ele in reversed(path): print(grid[ele[0]][ele[1]], " [", ele[0], ", ", ele[1], "]", sep = "") grid = [ [10, 7, 6, 3], [9, 8, 7, 6], [8, 4, 2, 7], [2, 2, 2, 8]] get_sequence(grid)
输入
[[10, 7, 6, 3], [9, 8, 7, 6], [8, 4, 2, 7], [2, 2, 2, 8]]
输出
Maximum length: 6 Sequence is: 10 [0, 0] 9 [1, 0] 8 [1, 1] 7 [1, 2] 6 [1, 3] 7 [2, 3] 8 [3, 3]