• Leetcode每日一题 54. 螺旋矩阵


    54. 螺旋矩阵

    给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

    示例 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]

    提示:

    m == matrix.length
    n == matrix[i].length
    1 <= m, n <= 10
    -100 <= matrix[i][j] <= 100

    以前写过,直接按圈遍历就行。

    每次遍历左上角往右下递增一层,右下角往左上角递减一层。注意控制跳出循环的条件,只要x1或y1其中一个大于x2,y2则跳出循环。

    比如:[1,2,3,4],[5,6,7,8]   x1,y1从 元素1 跳到元素6   x2,y2从元素8 跳到 元素3,此时已经遍历完成,如果不跳出循环,则会出现重复数据。

        

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            int n = matrix.size();
            int m = matrix[0].size();
            vector<int> ans;
    
            int x1 = 0 , y1 = 0;
            int x2 = n - 1, y2 = m - 1;
            
            while(true)
            {
                if(x1 > x2 || y1 > y2)
                {
                    break;
                }
    
                if(x1 == x2)
                {
                    for(int i = y1 ; i <= y2 ; i++)ans.push_back(matrix[x1][i]);
                    break;
                }
    
                if(y1 == y2)
                {
                    for(int i = x1 ; i <= x2 ; i++)ans.push_back(matrix[i][y1]);
                    break;
                }
    
                for(int i = y1 ; i < y2 ; i++)ans.push_back(matrix[x1][i]);
                for(int i = x1 ; i < x2 ; i++)ans.push_back(matrix[i][y2]);
                for(int i = y2 ; i > y1 ; i--)ans.push_back(matrix[x2][i]);
                for(int i = x2 ; i > x1 ; i--)ans.push_back(matrix[i][y1]);
    
                x1++;
                y1++;
                x2--;
                y2--;
            }
            
            return ans;
        }
    };

    对了,之前有看过一篇算法文章,说过这种类似的题目,这种题写不出的原因是在于什么,看的是我们对边界的概念是否清晰,就比如这个按圈遍历,我们是如何从右到左,从上到下遍历的,它的边界应该在哪停止,分析一下其实就很清楚,

    首先是对循环的把握 看到 for(int i = y1 ; i < y2 ; i++) 我们能得知什么,肯定是得知了这个遍历的范围为[y1,y2-1] (注意是闭区间),同理下面的就是[x1,x2-1] ,[y1 + 1 , y2] ,[x1 + 1 , x2],把它们合起来,是不是刚好就是一圈了呢,看下面这个图应该就更好理解了:

    只要确定了边界,这种题就非常好写了。

  • 相关阅读:
    HDU4652 Dice
    CF113D Museum / BZOJ3270 博物馆
    SHOI2013 超级跳马
    最基本的卷积与反演
    NOI2014 动物园题解
    SP11414 COT3
    new to do
    linux C++中宏定义的问题:error: unable to find string literal operator ‘operator""fmt’ with ‘const char [4]’, ‘long unsigned int’ arguments
    新装vs2010的问题:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    windows下删除虚拟串口的方法,以及解决串口使用中,无法变更设备串口号的问题
  • 原文地址:https://www.cnblogs.com/xiangqi/p/14537327.html
Copyright © 2020-2023  润新知