zoukankan      html  css  js  c++  java
  • LeetCode-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].

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            
            if(matrix.size()==0||matrix[0].size()==0)return vector<int>();
            int n=matrix.size();
            int m=matrix[0].size();
            vector<int>ret;
            int toward=0;
            int x=-1;
            int y=0;
            while(n>0&&m>0){
                if(toward==0){
                    for(int i=0;i<m;i++){
                        x++;
                        ret.push_back(matrix[y][x]);
                    }
                    n--;
                }
                else if(toward==1){
                    for(int i=0;i<n;i++){
                        y++;
                        ret.push_back(matrix[y][x]);
                    }
                    m--;
                }
                else if(toward==2){
                    for(int i=0;i<m;i++){
                        x--;
                        ret.push_back(matrix[y][x]);
                    }
                    n--;
                }
                else{
                    for(int i=0;i<n;i++){
                        y--;
                        ret.push_back(matrix[y][x]);
                    }
                    m--;
                }
                toward++;
                toward=toward%4;
            }
            return ret;
        }
    };
    View Code
  • 相关阅读:
    InnoDB On-Disk Structures(三)--Tablespaces (转载)
    InnoDB On-Disk Structures(二)--Indexes (转载)
    InnoDB On-Disk Structures(一)-- Tables (转载)
    UML之状态图
    UML之活动图
    UML交互图
    UML类图
    UML用况图
    UML OOA
    UML问题定义
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353079.html
Copyright © 2011-2022 走看看