• [LeetCode] Spiral Matrix


    The idea is just to add the elements in the spiral order. First the up-most row (u), then the right-most column (r), then the down-most row (d), and finally the left-most column (l). After finishing a row or a column, update the corresponding variable to continue the process.

    The code is as follows.

     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         if (matrix.empty()) return {};
     5         int m = matrix.size(), n = matrix[0].size();
     6         vector<int> spiral(m * n);
     7         int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
     8         while (true) {
     9             // up
    10             for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
    11             if (++u > d) break;
    12             // right
    13             for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
    14             if (--r < l) break;
    15             // down
    16             for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
    17             if (--d < u) break;
    18             // left
    19             for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
    20             if (++l > r) break;
    21         }
    22         return spiral;
    23     }
    24 };
  • 相关阅读:
    团队作业开发过程
    UVM基础之--------uvm_root
    UVM基础之------uvm_transaction
    UVM基础之----uvm_object
    UVM挑战及概述
    定制UVM Messages(参考)
    SV creation order
    IC验证概念总结
    win7 硬盘安装suse双系统启动顺序更改
    suse 下的gcc安装
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4719962.html
Copyright © 2020-2023  润新知