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].


上篇文章里有这个问题解决思路的说明,及说明的一个图做例子,这种思路是最中规中矩的思路,当然如果数学基础好,或者奇思妙想爆棚的主,会有自己独特的解法,这里不表。那么按照这种按层拨的方式解决的话,不同程序的差别就是具体实现上代码的工整性不同,这里借鉴了leetcode讨论区(老版)里的程序,还算工整。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> ivec;
        if(matrix.empty()) return ivec;
        int begin_rows = 0, end_rows = matrix.size() - 1;
        int begin_cols = 0, end_cols = matrix[0].size() - 1;
        while(1)
        {
            //up border: left -> right
            for(int i = begin_cols; i <= end_cols; ++i)
                ivec.push_back(matrix[begin_rows][i]);
        
            //right border: up -> down, 
            if(++begin_rows > end_rows)//can't go down anymore
            break;
            for(int j = begin_rows; j <= end_rows; ++j)
                ivec.push_back(matrix[j][end_cols]);
            //down border: right -> left
            if(--end_cols < begin_cols)
            break;
            for(int i = end_cols; i >= begin_cols; --i)
                ivec.push_back(matrix[end_rows][i]);
            //left border: down -> up
            if(--end_rows < begin_rows)
            break;
            for(int j = end_rows; j >= begin_rows; --j)
                ivec.push_back(matrix[j][begin_cols]);
            if(++begin_cols > end_cols)
            break;
        }
        return ivec;
    }
};

这里的每一步if 判断都是必不可少的,这也是跟Spiral Matrix II 不同的地方,虽然思路一致,但控制不一样,这里要考虑边界问题。这里再把那张图拿出来说明下:

Spiral Matrix_第1张图片

1) if(++begin_rows > end_rows) 说的是,比如只有第一行的时候,我们走到 5 就不往下走了,因为没有了。

2) if(--end_cols < begin_cols)说的是,比如只有一列的时候,比如上图的最后一列,我们走到 9 就不往左走了,因为没有了。

3)if(--end_rows < begin_rows)说的是,假如上图只有前两行,那么我们走到 16 就不往上走了,因为没有了。

4)if(++begin_cols > end_cols)说的是,假如上图只有前两列,那么 走到 16 就不能向右走了,因为没有了。

之所以会发生这种情况,是因为给定matrix的行列是任意的,这样就不能保证我们把程序中设定的上右下左四个方向都走遍了,所以每走一个新的方向前都的试探是否没走过(可行)。


你可能感兴趣的:(LeetCode,数学,Class,Matrix,traversal)