题解 | 螺旋矩阵

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix int整型vector<vector<>> 
     * @return int整型vector
     */
    vector<int> spiralOrder(vector<vector<int> >& matrix) {
        // write code here
        int m=matrix.size();
        vector<int> res;
        if(m==0)
        {
            return res;
        }
        int n=matrix[0].size();
        int top=0;
        int bottom=m-1;
        int left=0;
        int right=n-1;
        while(top<=bottom&&left<=right)
        {
            //从左到右
            for(int i=left;i<=right;i++)
            {
                res.push_back(matrix[top][i]);
            }
            top++;
            //从上往下
            for(int i=top;i<=bottom;i++)
            {
                res.push_back(matrix[i][right]);
            }
            right--;
            if(top<=bottom)//最后只有一行时,仅需从左到右即可
            {
                //从右往左
                for(int i=right;i>=left;i--)
                {
                res.push_back(matrix[bottom][i]);
                }
                bottom--;
            }
            if(left<=right)//只有最后一列时,仅需从上到下即可
            {
                //从下往上
                for(int i=bottom;i>=top;i--)
                {
                    res.push_back(matrix[i][left]);
                }
                left++;
            }
        }
        return res;

    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务