2020-06-05 LeetCode 面试题29 顺时针打印矩阵 C++

题目:面试题29. 顺时针打印矩阵

 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

 注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/

 思路:题目本身挺简单的,按照顺时针规律从里到外遍历就好了,问题就是对边界情况的处理比较麻烦,需要注意的有空矩阵、行向量、列向量等,自己写了个难看的就不贴了,想了半天也不知道怎么把特殊情况一般化。下面是官方题解,但是感觉也不够简洁,还是对行向量和列向量的情况进行了单独判断

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        //空矩阵
        if (matrix.empty()) 
            return {};
        //行列大小
        int rows = matrix.size(), columns = matrix[0].size();
        vector<int> ans;
        //上下左右的边界
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
        	//从左上往右上
            for (int j = left; j <= right; j++)
                ans.push_back(matrix[top][j]);
            //从右上往右下
            for (int i = top + 1; i <= bottom; i++) 
                ans.push_back(matrix[i][right]);
            //针对行向量和列向量的处理
            if (left < right && top < bottom) {
                //从右下往左下
                for (int j = right - 1; j > left; j--) 
                    ans.push_back(matrix[bottom][j]);
                //从左下往左上
                for (int i = bottom; i > top; i--) 
                    ans.push_back(matrix[i][left]);
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return ans;
    }
};

运行结果:
在这里插入图片描述
 还是码一下,以后复习的时候希望能找到简洁的实现。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章