class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
}
};
54. 螺旋矩阵
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
相似题目
原站题解
python3 解法, 执行用时: 32 ms, 内存消耗: 15 MB, 提交时间: 2022-08-02 15:46:28
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix or not matrix[0]: return list() rows, columns = len(matrix), len(matrix[0]) order = list() left, right, top, bottom = 0, columns - 1, 0, rows - 1 while left <= right and top <= bottom: for column in range(left, right + 1): order.append(matrix[top][column]) for row in range(top + 1, bottom + 1): order.append(matrix[row][right]) if left < right and top < bottom: for column in range(right - 1, left, -1): order.append(matrix[bottom][column]) for row in range(bottom, top, -1): order.append(matrix[row][left]) left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1 return order
python3 解法, 执行用时: 44 ms, 内存消耗: 15 MB, 提交时间: 2022-08-02 15:46:14
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix or not matrix[0]: return list() rows, columns = len(matrix), len(matrix[0]) visited = [[False] * columns for _ in range(rows)] total = rows * columns order = [0] * total directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] row, column = 0, 0 directionIndex = 0 for i in range(total): order[i] = matrix[row][column] visited[row][column] = True nextRow, nextColumn = row + directions[directionIndex][0], column + directions[directionIndex][1] if not (0 <= nextRow < rows and 0 <= nextColumn < columns and not visited[nextRow][nextColumn]): directionIndex = (directionIndex + 1) % 4 row += directions[directionIndex][0] column += directions[directionIndex][1] return order