zoukankan      html  css  js  c++  java
  • [LeetCode]Spiral Matrix

    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].

    很好理解的思路。每个循环来遍历一圈。

    确定圈的左上点的坐标(x1,y1)和右下点的坐标(x2,y2)。

    继续遍历的条件是(x2>=x1 && y2>=y1)。

    是不是很简单,也不容易错。

     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> result;
     5         if(matrix.size()==0 || matrix[0].size()==0) return result;
     6         int m=matrix.size(),n=matrix[0].size();
     7         int x1=0,y1=0,x2=m-1,y2=n-1;
     8         while(x2>=x1 & y2>=y1)
     9         {
    10             if(x2>=x1 & y2>=y1)
    11             {
    12                 for(int i=y1;i<=y2;i++) result.push_back(matrix[x1][i]);
    13                 x1++;
    14             }
    15             if(x2>=x1 & y2>=y1)
    16             {
    17                 for(int i=x1;i<=x2;i++) result.push_back(matrix[i][y2]);
    18                 y2--;
    19             }
    20             if(x2>=x1 & y2>=y1)
    21             {
    22                 for(int i=y2;i>=y1;i--) result.push_back(matrix[x2][i]);
    23                 x2--;
    24             }
    25             if(x2>=x1 & y2>=y1)
    26             {
    27                for(int i=x2;i>=x1;i--) result.push_back(matrix[i][y1]);
    28                 y1++; 
    29             }
    30         }
    31         return result;
    32     }
    33 };
  • 相关阅读:
    bat 批处理编写
    dos 命令
    反射
    反爬机制和破解方法汇总
    pandas
    谷歌历史浏览器下载
    python-----pip安装源选择(亲测有效)
    deepin 20.1 系统未安装pip
    python自带库-----os.path
    python 自带库---os库
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4796203.html
Copyright © 2011-2022 走看看