Sunday, August 2, 2015

054 - 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].
Hide Tags
Array
Hide Similar Problems
(M) Spiral Matrix II


其实这个比 Spiral Matrix II 复杂一些,因为并不是正方形的矩阵。
所以长宽要分开算,用了 m, n, len1, len2 来处理,
思路还是一样,每次取要读的行/列 (个数–1) 个数据,衔接回环。

单行或者单列的case,实际上是通过 top+bottom,或者 right + left 来合成的,
top读取前 n-1个, bottom补上第n个;或是 right 读取前 m-1个,left补上第m个
所以在 bottom 已经 left 的读取过程中要检查是否够数了,不然就会重复读取了。

还有一个特殊case就是边是奇数个数据的正方形的矩阵中,最中心的一个会取不到,
因为此时 len1 和 len2 都是 0,四个for循环都进不去,所以单独补了一个处理

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int>rst;
        int m=matrix.size();
        if(m)
        {
            int n=matrix[0].size();
            if(n)
            {
                int len1=n-1, len2=m-1, circle=0, tgt=m*n;
                while((len1>=0)&&(len2>=0)&&(tgt>=rst.size()))
                {
                    if(!len1&&!len2)
                        rst.push_back(matrix[circle][circle]);
                    else
                    {
                        //top
                        for(int ii=0; ii<len1; ++ii)
                            rst.push_back(matrix[circle][circle+ii]);


                        //right
                        for(int ii=0; ii<len2; ++ii)
                            rst.push_back(matrix[circle+ii][circle+len1]);


                        //bottom
                        for(int ii=0; ii<len1; ++ii)
                        {
                            rst.push_back(matrix[circle+len2][circle+len1-ii]);
                            if(tgt==rst.size())  //check for case like matrix has only one row
                                break;

                        }
                       
                        //left
                        for(int ii=0; ii<len2; ++ii)
                        {
                            rst.push_back(matrix[circle+len2-ii][circle]);
                            if(tgt==rst.size())  //check for case like matrix has only one column
                                break;

                        }
                    }


                    len1 -= 2, len2 -= 2;
                    circle++;
                }
            }
        }
        return rst;
    }
};


0 ms.

1 comment: