• leetcode 54. Spiral Matrix


    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]
     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> res;
     5         int m = matrix.size();
     6         if (m == 0)
     7             return res;
     8         int n = matrix[0].size();
     9         int cnt = 0;
    10         res.resize(m * n);
    11         int start_row = 0, start_col = 0, end_row = m - 1, end_col = n - 1;
    12         while (cnt < m * n) {
    13             for (int j = start_col; cnt < m * n && j <= end_col; j++) {
    14                 res[cnt++] = matrix[start_row][j];
    15             }
    16             for (int i = start_row + 1; cnt < m * n && i <= end_row; i++) {
    17                 res[cnt++] = matrix[i][end_col];
    18             }
    19             for (int j = end_col - 1; cnt < m * n && j >= start_col; j--) {
    20                 res[cnt++] = matrix[end_row][j];
    21             }
    22             for (int i = end_row - 1; cnt < m * n && i > start_row; i--) {
    23                 res[cnt++] = matrix[i][start_col];
    24             }
    25             start_row++;
    26             start_col++;
    27             end_row--;
    28             end_col--;
    29         }
    30         return res;
    31     }
    32 };
  • 相关阅读:
    linux rcu
    linux下的进程、网络、性能监控命令
    使用optimizely做A/B测试
    使用logstash收集日志的可靠性验证
    LAMP-HTTPD的安装全步骤
    Iptables Save
    linux-ftp
    远程桌面验证问题,函数错误-windows
    ESXIroot密码重置
    centos or windows 双系统
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11530709.html
Copyright © 2020-2023  润新知