• LeetCode54 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]. (Medium)

    分析:

    题目没有什么复杂的算法要应用,就是一行一列输出,处理好细节即可。

    比较清晰的写法是搞一个rowBegin, rowEnd, colBegin, colEnd, 并在处理完一行/一列后更新值,并判断是否仍然满足 rowBegin <= rowEnd && colBegin <= colEnd

    代码:

     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 m = matrix.size(), n = matrix[0].size();
     9         int rowBegin = 0, rowEnd = m - 1, colBegin = 0, colEnd = n - 1;
    10         while (rowBegin <= rowEnd && colBegin <= colEnd) {
    11             for (int i = colBegin; i <= colEnd; ++i ) {
    12                 result.push_back(matrix[rowBegin][i]);
    13             }
    14             rowBegin++;
    15             if (rowBegin > rowEnd) {
    16                 break;
    17             }
    18             for (int i = rowBegin; i <= rowEnd; ++i) {
    19                 result.push_back(matrix[i][colEnd]);
    20             }
    21             colEnd--;
    22             if (colBegin > colEnd) {
    23                 break;
    24             }
    25             for (int i = colEnd; i >= colBegin; --i) {
    26                 result.push_back(matrix[rowEnd][i]);
    27             }
    28             rowEnd--;
    29             if (rowBegin > rowEnd) {
    30                 break;
    31             }
    32             for (int i = rowEnd; i>= rowBegin; --i) {
    33                 result.push_back(matrix[i][colBegin]);
    34             }
    35             colBegin++;
    36         }
    37         return result;
    38     }
    39 };
  • 相关阅读:
    BZOJ 1492 [NOI2007]货币兑换Cash
    BZOJ 2285 [Sdoi2011]保密
    BZOJ 2962 序列操作
    BZOJ 3197 [Sdoi2013]assassin
    BZOJ 3131 [Sdoi2013]淘金
    BZOJ 3532 [Sdoi2014]Lis
    BZOJ 1923 [Sdoi2010]外星千足虫
    BZOJ 4855 [Jsoi2016]轻重路径
    BZOJ 4289 PA2012 Tax
    微信开发之 微信支付
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5886915.html
Copyright © 2020-2023  润新知