本文共 1890 字,大约阅读时间需要 6 分钟。
给定一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例1:输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5]
示例2:输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]输出:[1,2,3,4,8,12,11,10,9,5,6,7]
我们可以通过逐层遍历矩阵来实现顺时针打印。具体步骤如下:
#includeusing namespace std;vector spiralOrder(vector > matrix) { vector res; if (matrix.empty()) return res; int left = 0, right = matrix[0].size() - 1; int top = 0, bottom = matrix.size() - 1; while (true) { // 从左到右 for (int i = left; i <= right; ++i) { res.push_back(matrix[top][i]); } if (++top > bottom) break; // 从上到下 for (int i = top; i <= bottom; ++i) { res.push_back(matrix[i][right]); } if (left > --right) break; // 从右到左 for (int i = right; i >= left; --i) { res.push_back(matrix[bottom][i]); } if (top > --bottom) break; // 从下到上 for (int i = bottom; i >= top; --i) { res.push_back(matrix[i][left]); } if (++left > right) break; } return res;}
left
、right
、top
、bottom
,分别表示矩阵的左、右、上、下边界。while
循环逐层遍历矩阵。这个方法利用了矩阵的转置和翻转特性:
zip(*matrix)
实现。[::-1]
。这种方法非常简洁,易于实现。
def spiralOrder(matrix): res = [] while matrix: res += matrix.pop(0) matrix = list(zip(*matrix))[::-1] return res
while
循环处理非空矩阵。以上是两种解决方案的实现方式。第一种方法通过逐层遍历实现,逻辑清晰但代码稍微复杂;第二种方法利用了矩阵的转置和翻转特性,实现简洁但对转置操作有一定的性能消耗。根据具体需求选择使用哪种方法都可以。
转载地址:http://ireg.baihongyu.com/