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

    分析

    举个例子自己从头到尾把数字列出来,很容易就找到规律了:
    假设一维数组的坐标为x,取值范围是xMin~xMax;二维数组的坐标为y,取值范围是yMin~yMax。(也就是数组表示为int[y][x])
    1. 从左到右,y=yMin,x: xMin->xMax,yMin++
    2. 从上到下,x=xMax,y: yMin->yMax,xMax--
    3. 从右到左,y=yMax,x: xMax->xMin,yMax--
    4. 从下到上,x=xMin,y: yMax->uMin,xMin++
    结束条件,xMin==xMax或者yMin==yMax
     
    还要要注意的地方:空数组的情况要处理。
     
    C++实现代码:
    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Solution
    {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix)
        {
            if(matrix.empty()||matrix[0].empty())
                return vector<int>();
            vector<int> ret;
            int xmin=0;
            int ymin=0;
            int xmax=matrix[0].size()-1;
            int ymax=matrix.size()-1;
            ret.push_back(matrix[0][0]);
            int i=0,j=0;
            while(1)
            {
                while(i<xmax)
                    ret.push_back(matrix[j][++i]);
                if(++ymin>ymax)
                    break;
                while(j<ymax)
                    ret.push_back(matrix[++j][i]);
                if(--xmax<xmin)
                    break;
                while(i>xmin)
                    ret.push_back(matrix[j][--i]);
                if(--ymax<ymin)
                    break;
                while(j>ymin)
                    ret.push_back(matrix[--j][i]);
                if(++xmin>xmax)
                    break;
            }
            return ret;
        }
    };
    
    int main()
    {
        Solution s;
        vector<vector<int> > vec= {{1,2}};
        vector<int> result=s.spiralOrder(vec);
        for(auto a:result)
            cout<<a<<" ";
        cout<<endl;
    }
  • 相关阅读:
    Bzoj1499: [NOI2005]瑰丽华尔兹
    Bzoj1016: [JSOI2008]最小生成树计数
    清橙A1212:剪枝
    SPOJ1825:Free tour II
    http://www.freepik.com/
    A Guide To Transclusion in AngularJS
    styling-customizing-file-inputs
    You Don't Know JS: this & Object Prototypes
    git中https和SSH的区别
    difference between match and exec
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4135897.html
Copyright © 2011-2022 走看看