zoukankan      html  css  js  c++  java
  • 54. Spiral Matrix(剑指offer 19)



    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]
    

    注意只有一行或者只有一列的情况

    if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> list ;
            if(matrix.size()==0) return list;
            int rows =matrix.size();
            int cols = matrix[0].size();
            int c1 = 0,c2 = cols-1;
            int r1 = 0,r2 = rows-1;
            
            while(r1<=r2&&c1<=c2){
                for(int c=c1;c<=c2;c++) list.push_back(matrix[r1][c]);
                for(int r=r1+1;r<=r2;r++) list.push_back(matrix[r][c2]);
                if (r1 < r2 && c1 < c2) {//避免只有一行,c1==c2的情况,避免只有一列,r1==r2的情况
                    for(int c=c2-1;c>=c1+1;c--) list.push_back(matrix[r2][c]);
                    for(int r=r2;r>=r1+1;r--) list.push_back(matrix[r][c1]);
                }
                c1++;c2--;r1++;r2--;
            }
            return list;
        }
    };
  • 相关阅读:
    次小生成树
    [bzoj5329] P4606 [SDOI2018]战略游戏
    CF487E Tourists
    P3225 [HNOI2012]矿场搭建
    CF #636 (Div. 3) 对应题号CF1343
    P3469 [POI2008]BLO-Blockade
    大假期集训模拟赛12
    大假期集训模拟赛11
    大假期集训模拟赛10
    小奇画画——BFS
  • 原文地址:https://www.cnblogs.com/zle1992/p/10219079.html
Copyright © 2011-2022 走看看