• 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     int min(int a, int b){
     2         if(a < b)
     3             return a;
     4         return b;
     5     }
     6     vector<int> spiralOrder(vector<vector<int> > &matrix) {
     7         // IMPORTANT: Please reset any member data you declared, as
     8         // the same Solution instance will be reused for each test case.
     9         vector<int> result;
    10         result.clear();
    11         int m = matrix.size();
    12         if(m == 0)
    13             return result;
    14         int n = matrix[0].size();
    15         if(n == 0)
    16             return result;
    17         int i,j;
    18         for(i = 0; i < min(m,n)/2; i++){
    19             for(j = i; j < n-1-i; j++)
    20                 result.push_back(matrix[i][j]);
    21             for(j = i; j < m-1-i; j++)
    22                 result.push_back(matrix[j][n-1-i]);
    23             for(j = n-1-i; j > i; j--)
    24                 result.push_back(matrix[m-1-i][j]);
    25             for(j = m-1-i; j > i; j--)
    26                 result.push_back(matrix[j][i]);
    27         }
    28         if(min(m,n)%2 == 1){
    29             if(m < n){
    30                 for(i = m/2; i < n-m/2; i++)
    31                     result.push_back(matrix[m/2][i]);
    32             }
    33             else{
    34                 for(i = n/2; i < m-n/2; i++)
    35                     result.push_back(matrix[i][n/2]);
    36             }
    37         }
    38         return result;
    39     }
  • 相关阅读:
    显卡关键词
    为照顾IE6尽量不要margin和padding
    如何保证一个类只有一个实例(1)
    显示列表(display list)
    AutoCAD2007与Office2007冲突
    虚函数(1)
    字符串对象的属性
    细读cow.osg
    常量折叠(const folding)与复写传播 (copy propagation)
    .NET Framework 3.5 sp1离线安装
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3410091.html
Copyright © 2020-2023  润新知