19 顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例:
输入:
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12],
[13,14,15,16]]
输出: [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]解题思路
核心思想:使用四条边界(上、下、左、右)来控制打印顺序。
关键步骤:
- 初始化四个边界:top=0, bottom=rows-1, left=0, right=cols-1
- 按照"从左到右→从上到下→从右到左→从下到上"的顺序打印
- 每打印一边,对应的边界收缩
- 当边界不满足条件时停止
时间复杂度:O(m*n) 空间复杂度:O(1)
Python 实现
python
def print_matrix(matrix):
"""
顺时针打印矩阵
Args:
matrix: 二维矩阵
Returns:
list: 顺时针打印的结果
"""
if not matrix or not matrix[0]:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# 从左到右
for i in range(left(left, right + 1):
result.append(matrix[top][i])
top += 1
# 从上到下
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
# 从右到左(需要检查top <= bottom)
if top <= bottom:
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
# 从下到上(需要检查left <= right)
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
# 测试代码
if __name__ == "__main__":
# 测试用例1: 4x4矩阵
matrix1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print("矩阵1:", print_matrix(matrix1))
# 测试用例2: 3x4矩阵
matrix2 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print("矩阵2:", print_matrix(matrix2))
# 测试用例3: 单行
matrix3 = [[1, 2, 3, 4]]
print("矩阵3:", print_matrix(matrix3))
# 测试用例4: 单列
matrix4 = [[1], [2], [3], [4]]
print("矩阵4:", print_matrix(matrix4))
# 输出:
# 矩阵1: [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
# 矩阵2: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
# 矩阵3: [1, 2, 3, 4]
# 矩阵4: [1, 2, 3, 4]图解
示例矩阵:
0 1 2 3
0 [ 1 2 3 4 ]
1 [ 5 6 7 8 ]
2 [ 9 10 11 12 ]
3 [13 14 15 16 ]
打印顺序:
第一圈 (top=0, bottom=3, left=0, right=3):
→ 从左到右: 1, 2, 3, 4
↓ 从上到下: 8, 12, 16
← 从右到左: 15, 14, 13
↑ 从下到上: 9, 5
边界更新: top=1, bottom=2, left=1, right=2
第二圈 (top=1, bottom=2, left=1, right=2):
→ 从左到右: 6, 7
↓ 从上到下: 11
← 从右到(从右到左: 10
边界更新: top=2, bottom=1, left=2, right=1
条件不满足,结束
最终输出: [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]