[LeetCode]54. Spiral Matrix

旋转打印矩阵

Posted by JinFei on February 17, 2020

题目描述

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

Example1:

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

Note:

You may assume all input has valid answer.

解题思路

  • 循环的条件要记得 cycle = (min(row, col) - 1) / 2 + 1
  • 最后两个防止重复的要记得 row - i - 1 != i   col - i - 1 != i
  • 记得将matrix[i][j] // 下标换成对应的
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int row = matrix.size();
        vector<int> res;
        if(row == 0){
            return res;
        }
        int col = matrix[0].size();
        if(row == 1 && col == 1){
            res.push_back(matrix[0][0]);
            return res;
        }
        int cycle = (min(row, col) - 1) / 2 + 1;
        
        for(int i = 0; i < cycle; i++){
            for(int j = i; j < col - i; j++){
                res.push_back(matrix[i][j]);
            }
            for(int j = i + 1; j < row - i; j++){
                res.push_back(matrix[j][col - 1 - i]);
            }
            for(int j = col - i - 2; j >= i && row - 1 - i != i; j--){
                res.push_back(matrix[row - i - 1][j]);
            }
            for(int j = row - i - 2; j > i && col - 1 - i != i; j--){
                res.push_back(matrix[j][i]);
            }
        }
        return res;
    }
};