[leetcode] Spiral Matrix


Spiral Matrix

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

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

螺旋矩阵输出。

一开始我的思路是用i从0到m*n递增,然后将i映射到matrix[r][c]的r,c变量,即寻找一种映射关系就好。后来没想出来。

于是直接用直觉的方法,一圈一圈地扫。

需要注意每次扫的起点[r][c],以及需要扫多少步,row, column。处理好细节,比如r++,c–神马的。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> re;
        int row = matrix.size();
        if(row == 0){
            return re; // empty input
        }
        int column = matrix[0].size();
        int r = 0;
        int c = 0;
        while(row > 0 && column > 0){
            //move right
            for(int i = 0; i < column; i++){
                re.push_back(matrix[r][c]);
                c++;
            }
            c--;
            r++;
            if (--row == 0) break;
            //move down
            for(int i = 0; i < row; i++){
                re.push_back(matrix[r][c]);
                r++;
            }
            r--;
            c--;
            if (--column == 0) break;
            //move left
            for(int i = 0; i < column; i++){
                re.push_back(matrix[r][c]);
                c--;
            }
            c++;
            r--;
            if (--row == 0) break;
            //move up
            for(int i = 0; i < row; i++){
                re.push_back(matrix[r][c]);
                r--;
            }
            r++;
            c++;
            if (--column == 0) break;
        }
        return re;
    }
};

Untitled

 

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.