zoukankan      html  css  js  c++  java
  • Leetcode 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]
    
     1 class Solution {
     2     public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         // 存储结果
     5         vector<int> result;
     6         // 边界条件
     7         if (matrix.empty())
     8             return result;
     9         // 二维矩阵行列
    10         int rows = matrix.size();
    11         int cols = matrix[0].size();
    12         // 圈的四个角标
    13         int left = 0;
    14         int right = cols - 1;
    15         int top = 0;
    16         int btm = rows - 1;
    17         // 循环打印圈
    18         while (left <= right && top <= btm){             // 循环条件:
    19             // 圈的第一步
    20             for (int i = left; i <= right; ++i)                // 第一步循环条件
    21                 result.push_back(matrix[top][i]);       // 第一步坐标
    22             // 圈的第二步
    23             if (top<btm)                                 // 第二步边界条件
    24                 for (int i = top + 1; i <= btm; ++i)             // 第二步循环条件
    25                     result.push_back(matrix[i][right]); // 第二步坐标
    26             // 圈的第三步
    27             if (top<btm && left<right)                   // 第三步边界条件
    28                 for (int i = right - 1; i >= left; --i)          // 第三步循环条件
    29                     result.push_back(matrix[btm][i]);   // 第三步坐标
    30             // 圈的第四步
    31             if (top + 1<btm && left<right)                 // 第四步边界条件
    32                 for (int i = btm - 1; i >= top + 1; --i)           // 第四步循环条件
    33                     result.push_back(matrix[i][left]);  // 第四步坐标
    34 
    35             ++left; --right; ++top; --btm;
    36         }
    37         return result;
    38     }
    39 };
  • 相关阅读:
    Zabbix的前台SQL注射漏洞利用
    LeetCode OJ--Permutation Sequence *
    LeetCode OJ--Next Permutation *
    LeetCode OJ--Permutations II
    LeetCode OJ--Permutations *
    小算法-计算下一个排列
    LeetCode OJ--Gas Station**
    LeetCode OJ--Insert Interval **
    LeetCode OJ--Search Insert Position
    Ruby自动化测试(操作符的坑)
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10163035.html
Copyright © 2011-2022 走看看