代码题(37)— 螺旋矩阵(矩阵打印)

1、54. 螺旋矩阵

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

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

示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
   思想:用左上和右下的坐标定位出一次要旋转打印的数据,一次旋转打印结束后,往对角分别前进和后退一个单位。
    提交代码时,主要的问题出在没有控制好后两个for循环,需要加入条件判断,防止出现单行或者单列的情况。
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& mat) {
        vector<int> res;
        if(mat.empty())
            return res;
        int m = mat.size();
        int n = mat[0].size();
        
        int left = 0, right = n-1, high = 0, low = m-1;
        while(left<=right && high<=low)
        {
            for(int i=left;i<=right;++i)
                res.push_back(mat[high][i]);
            for(int i=high+1;i<=low;++i)
                res.push_back(mat[i][right]);
            
            for(int i=right-1;i>=left && low>high;--i)//判断条件,避免出现单行情况(出现则不运行这里)
                res.push_back(mat[low][i]);
            
            for(int i=low-1;i>high && right>left;--i)//判断条件,避免出现单列情况(出现则不运行这里)
                res.push_back(mat[i][left]);
            left++,high++,right--,low--;
        }
        return res;
    }
};

 2、59. 螺旋矩阵 II

 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n) );
        if(n<=0)
            return res;
        int left=0,right=n-1;
        int high=0,low=n-1;
        int num = 1;
        while(left<=right && high<=low)
        {
            for(int i=left;i<=right;++i)
                res[high][i] = num++;
            for(int i=high+1;i<=low;++i)
                res[i][right] = num++;
            for(int i=right-1;i>=left && high<low;--i)
                res[low][i] = num++;
            for(int i=low-1;i>high && left<right;--i)
                res[i][left] = num++;
            left++,high++,right--,low--;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/eilearn/p/9429602.html