• [LeetCode]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].

    解题思路:

     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         }
     8         int left = 0;
     9         int right = matrix[0].size() - 1;
    10         int up = 0;
    11         int down = matrix.size() - 1;
    12         
    13         int n = matrix.size() * matrix[0].size();
    14         
    15         while (true) {
    16             for (int i = left; i <= right; ++i) {
    17                 result.push_back(matrix[up][i]);
    18                 --n;
    19             }
    20             if (n <= 0) {
    21                 break;
    22             }
    23             
    24             up += 1;
    25             for (int i = up; i <= down; ++i) {
    26                 result.push_back(matrix[i][right]);
    27                 --n;
    28             }
    29             if (n <= 0) {
    30                 break;
    31             }
    32             
    33             right -= 1;
    34             for (int i = right; i >= left; --i) {
    35                 result.push_back(matrix[down][i]);
    36                 --n;
    37             }
    38             if (n <= 0) {
    39                 break;
    40             }
    41         
    42             down -= 1;
    43             for (int i = down; i >= up; --i) {
    44                 result.push_back(matrix[i][left]);
    45                 --n;
    46             }
    47             left += 1;
    48             
    49             if (n <= 0) {
    50                 break;
    51             }
    52         }
    53         
    54         return result;
    55     }
    56 };
  • 相关阅读:
    学习进度条
    软件工程期末总结
    实验四 主存空间的分配与回收
    学术诚信与道德
    《构建之法》第八、九、十章读后感
    实验三、进程调度模拟程序实验
    《构建之法》第六七章读后感
    Scrum团队成立3.0
    0428-项目再开发2.0
    作业调度模拟程序
  • 原文地址:https://www.cnblogs.com/skycore/p/5269438.html
Copyright © 2020-2023  润新知