打印螺旋矩阵

螺旋矩阵

http://www.nowcoder.com/questionTerminal/7edf70f2d29c4b599693dc3aaeea1d31

由于行列不相等,因此定义四个变量用于记录边界:

  • 左边界left
  • 右边界right
  • 上边界top
  • 下边界bottom

然后以top和left基准层层打印,值得注意的是,为了避免重复打印,我们需要在打印下边和左边时额外判断一下top和bottom以及left和right是否相等:

//
// Created by jt on 2020/9/29.
//
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        if (matrix.empty()) return res;
        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;
        while (top < (matrix.size()+1) / 2 && left < (matrix[0].size()+1) / 2) {
            // 上
            for (int i = left; i <= right; ++i) {
                res.push_back(matrix[top][i]);
            }
            // 右
            for (int i = top + 1; i <= bottom; ++i) {
                res.push_back(matrix[i][right]);
            }
            // 下,注意这里的top!=bottom
            for (int i = right - 1; top != bottom && i >= left; --i) {
                res.push_back(matrix[bottom][i]);
            }
            // 左,注意这里的left!=right
            for (int i = bottom - 1; left != right && i >= top + 1; --i) {
                res.push_back(matrix[i][left]);
            }
            ++top, --bottom, ++left, --right;
        }
        return res;
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

头像
04-29 10:53
已编辑
东北大学 自动化类
点赞 评论 收藏
转发
11 1 评论
分享
牛客网
牛客企业服务