zoukankan      html  css  js  c++  java
  • 54. Spiral Matrix

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    For example, Given the following matrix:

    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    

    You should return [1,2,3,6,9,8,7,4,5].

    给定m × n个元素(m行,n列)的矩阵,按照螺旋顺序返回矩阵的所有元素。

    例如,给定以下矩阵:

    [ 
     [1,2,3],
     [4,5,6],
     [7,8,9] 
    ]
    

    你应该返回[1,2,3,6,9,8,7,4,5]

    (1)思想1:顺着spiralorder剥皮,up->right->bottom->left. 用四个变量x1, x2, y1, y2 控制上下左右边界。注意循环条件为x1<=x2 && y1<= y2,另外注意每行和每列输出的范围,代码如下:

     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> result;
     5         if(matrix.size()==0)
     6             return result;
     7         int x1=0;
     8         int y1=0;
     9         int x2=matrix.size()-1;
    10         int y2=matrix[0].size()-1;
    11         while(x1<=x2 && y1<=y2)
    12         {
    13             for(int j=y1;j<=y2;j++)
    14                 result.push_back(matrix[x1][j]);
    15             for(int i=x1+1;i<=x2;i++)
    16                 result.push_back(matrix[i][y2]);
    17             if(x2!=x1)
    18             {
    19                 for(int j=y2-1;j>=y1;j--)
    20                     result.push_back(matrix[x2][j]);
    21             }
    22             if(y2!=y1)
    23             {
    24                 for(int i=x2-1;i>x1;i--)
    25                     result.push_back(matrix[i][y1]);
    26             }
    27             x1++; y1++;
    28             x2--; y2--;
    29         }
    30         return result;
    31     }
    32 };
  • 相关阅读:
    js正则表达式 (.+)与(.+?)
    javaScript中的继承
    理解javascript中event loop,
    vue3-provide/inject 注入
    javaScript设计模式
    javaScript语言精粹--函数
    vue在数据data里面引入图片语法是require("")
    查看分支
    vue项目里面预览下载附件
    小程序组件中传值的几种方式
  • 原文地址:https://www.cnblogs.com/sword-/p/7997816.html
Copyright © 2011-2022 走看看