54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

方法1: Layer-by-Layer

官方题解:https://leetcode.com/problems/spiral-matrix/solution/

思路:

用四个变量标记上下左右的边界,每次遍历过一条边之后都将这一行/列排除。比如遍历完红色边之后firstRow下移,遍历绿色之后,lastCol左移,etc。循环条件就是firstRow <= lastRow, firstCol <= lastCol。当然这是不够的,还要在每次循环的中间随时判断是否break。以下图为栗子,边界条件出现在图二画出的情况。也就是说,只要当挪动某一行之后发现first/last的顺序被颠倒了,不管是行还是列,说明都刚刚遍历完了最内层,没有必要再继续,随时break。究竟哪个方向先break取决于长方形的形状。
在这里插入图片描述

易错点

  1. 循环内部的退出条件

Complexity

Time complexity: O(N), where N is the total number of elements in the input matrix. We add every element in the matrix to our final answer.
Space complexity: O(N), the information stored in ans.

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result = {};
        if (matrix.empty() || matrix[0].empty()) return result;
        int firstRow = 0;
        int lastRow = matrix.size() - 1;
        int firstCol = 0;
        int lastCol = matrix[0].size() - 1;
        
        while(firstRow <= lastRow && firstCol <= lastCol){
            for (int i = firstCol; i <= lastCol; i++){
                result.push_back(matrix[firstRow][i]);
            }
            firstRow++;

            if (firstCol <= lastCol){
                for (int i = firstRow; i <= lastRow; i++){
                    result.push_back(matrix[i][lastCol]);
                }
            }
            lastCol--;
            
            if (firstRow <= lastRow){
                for (int i = lastCol; i>= firstCol; i--) {
                    result.push_back(matrix[lastRow][i]);
                }
                lastRow--;
            }
            
            if (firstCol <= lastCol){
                 for (int i = lastRow; i >= firstRow; i--){
                    result.push_back(matrix[i][firstCol]);
                }
                firstCol++;
            }
           
        }
        
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值