如何从(0,0)开始逆时针遍历N×M矩阵并确定最后元素
从(0,0)开始逆时针遍历N×M矩阵的方法及最后元素确定
逆时针遍历的核心逻辑
逆时针遍历采用分层螺旋的方式,从矩阵外层到内层逐圈处理,每一圈包含四个方向的遍历步骤:
- 从当前层的顶部行,左→右遍历(起点(0,0)即第一圈的顶部行首元素)
- 从当前层的右侧列,上→下遍历(跳过已遍历的顶部行元素)
- 若当前层的底部行未与顶部行重合,从底部行右→左遍历(跳过已遍历的右侧列元素)
- 若当前层的左侧列未与右侧列重合,从左侧列下→上遍历(跳过已遍历的底部行和顶部行元素)
完成一圈后,收缩边界(顶部行+1、右侧列-1、底部行-1、左侧列+1),重复上述步骤直到所有元素遍历完成。
示例:3×4矩阵遍历过程
0 1 2 3 4 5 6 7 8 9 10 11
遍历顺序:0→1→2→3→7→11→10→9→8→4→5→6,最终最后一个元素为6。
代码实现(Python)
以下代码实现了逆时针遍历,并返回最后一个元素:
def get_last_counterclockwise(matrix): if not matrix or not matrix[0]: return None n, m = len(matrix), len(matrix[0]) top, bottom = 0, n - 1 left, right = 0, m - 1 last_element = None while top <= bottom and left <= right: # 左→右遍历顶部行 for j in range(left, right + 1): last_element = matrix[top][j] top += 1 # 上→下遍历右侧列 for i in range(top, bottom + 1): last_element = matrix[i][right] right -= 1 # 右→左遍历底部行 if top <= bottom: for j in range(right, left - 1, -1): last_element = matrix[bottom][j] bottom -= 1 # 下→上遍历左侧列 if left <= right: for i in range(bottom, top - 1, -1): last_element = matrix[i][left] left += 1 return last_element # 测试示例 matrix_3x4 = [[0,1,2,3],[4,5,6,7],[8,9,10,11]] print(get_last_counterclockwise(matrix_3x4)) # 输出6 matrix_2x4 = [[0,1,2,3],[4,5,6,7]] print(get_last_counterclockwise(matrix_2x4)) # 输出4 matrix_4x3 = [[0,1,2],[3,4,5],[6,7,8],[9,10,11]] print(get_last_counterclockwise(matrix_4x3)) # 输出7
直接推导最后一个元素的规律
若不想通过遍历获取最后元素,可根据矩阵行数N和列数M的关系直接推导:
设min_dim = min(N, M),max_dim = max(N, M),矩阵元素按行优先填充(即matrix[i][j] = i*M + j):
1. 当min_dim为奇数时
- 若
N ≤ M:最后元素坐标为(min_dim//2, max_dim - 1 - min_dim//2),值为(min_dim//2)*M + (max_dim - 1 - min_dim//2) - 若
M < N:最后元素坐标为(max_dim - 1 - min_dim//2, min_dim//2),值为(max_dim - 1 - min_dim//2)*M + min_dim//2
2. 当min_dim为偶数时
- 若
N ≤ M:最后元素坐标为(min_dim//2, min_dim//2 - 1),值为(min_dim//2)*M + (min_dim//2 - 1) - 若
M < N:最后元素坐标为(min_dim//2, 0),值为(min_dim//2)*M
(注:上述规律基于行优先填充的矩阵,若矩阵元素填充方式不同,只需替换坐标对应的元素计算逻辑即可)
内容的提问来源于stack exchange,提问作者Deril Raju
相关产品推荐
相关产品推荐

