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

题目解析:

方案一:

题目要求顺时针输出矩阵元素。没有什么特别的方法,行列行列求就行了。我定义的circle为进行到第几圈。代码如下

void SpiralOrder(int arr[][N],int m)
{
    int circle;
    if(m%2)
        circle = m/2+1;
    else
        circle = m/2;
    for(int k = 0;k<circle;k++){
        int i = k;
        int j;
        for(int j = k;j <= N-k-1;j++)
            printf("%d ",arr[i][j]);
        j = N-k-1;
        for(i = k+1;i <= m-k-1;i++)
            printf("%d ",arr[i][j]);
        i = m-k-1;
        for(j = N-k-2;j >= k;j--)
            printf("%d ",arr[i][j]);
        j = k;
        for(i = m-k-2;i > k;i--)
            printf("%d ",arr[i][j]);
    }
}



方案二:

后来碰到有高手说用DFS。这就太经典了,一个看似没任何技术含量的问题,通过算法就能得到简化。值得学习:

http://www.cnblogs.com/remlostime/archive/2012/11/18/2775708.html

具体的思路有待去考虑,不过方法很值得提倡!

class Solution {
private:
    int step[4][2];
    vector<int> ret;
    bool canUse[100][100];
public:
    void dfs(vector<vector<int> > &matrix, int direct, int x, int y)
    {
        for(int i = 0; i < 4; i++)
        {
            int j = (direct + i) % 4;
            int tx = x + step[j][0];
            int ty = y + step[j][1];
            if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty])
            {
                canUse[tx][ty] = false;
                ret.push_back(matrix[tx][ty]);                
                dfs(matrix, j, tx, ty);               
            }            
        }
    }
    
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        step[0][0] = 0;
        step[0][1] = 1;
        step[1][0] = 1;
        step[1][1] = 0;
        step[2][0] = 0;
        step[2][1] = -1;
        step[3][0] = -1;
        step[3][1] = 0;
        ret.clear();
        memset(canUse, true, sizeof(canUse));
        dfs(matrix, 0, 0, -1);
        
        return ret;
    }
};



点赞