Spiral Matrix(输出螺旋矩阵)

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

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
/* 定义四个方向:
 *以及四个边界值 left right up down
 *
 * */
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty())  return {};
        int row=matrix.size(), col=matrix[0].size(),left=0, right=col-1, up=0, down=row-1,index=0;
        vector<int> ret(row*col, 0);
        // k=0,1,2,3对应向右 向下 向左 向上
        for(int k=0;index<row*col;k=(k+1)%4){
            switch (k){
                case 0:
                    for(int j=left;j<=right;j++)    ret[index++]=matrix[up][j];
                    up++;break;
                case 1:
                    for(int i=up;i<=down;i++)   ret[index++]=matrix[i][right];
                    right--;break;
                case 2:
                    for(int j=right;j>=left;j--)    ret[index++]=matrix[down][j];
                    down--;break;
                case 3:
                    for(int i=down;i>=up;i--)   ret[index++]=matrix[i][left];
                    left++;
                    break;
            }
        }
        return ret;

    }
};

猜你喜欢

转载自blog.csdn.net/futangxiang4793/article/details/88876030