📅  最后修改于: 2023-12-03 14:54:29.665000             🧑  作者: Mango
本文介绍如何在一个二维矩阵中找到并打印出第 K 个边界。这个问题可以通过遍历矩阵边界的方式来解决。
我们可以按照以下步骤来解决这个问题:
rows
,列数为 cols
。def print_kth_boundary(matrix, K):
rows = len(matrix)
cols = len(matrix[0])
# 定义矩阵边界
top = 0
bottom = rows - 1
left = 0
right = cols - 1
# 根据 K 值确定需要打印的边界
if K > 0:
start_row, start_col, end_row, end_col = top, left, bottom, right
else:
start_row, start_col, end_row, end_col = top, right, bottom, left
# 打印边界元素
boundary = []
# 打印上边界
for col in range(start_col, end_col + 1):
boundary.append(matrix[start_row][col])
# 打印右边界
for row in range(start_row + 1, end_row + 1):
boundary.append(matrix[row][end_col])
# 打印下边界
for col in range(end_col - 1, start_col - 1, -1):
boundary.append(matrix[end_row][col])
# 打印左边界
for row in range(end_row - 1, start_row, -1):
boundary.append(matrix[row][start_col])
return boundary
# 示例用法
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
K = 1
result = print_kth_boundary(matrix, K)
print(result)