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].

    struct Direction
    {
        int x;
        int y;
        Direction()
        {}
        Direction(int x,int y)
        {
            this->x=x;
            this->y=y;
        }
    };
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) 
        {
            vector<int> result;
            //find max        
            int m=matrix.size();
            if(m==0return result;
            int n=matrix[0].size();
            
            int FLAG=matrix[0][0];
            for(int i=0;i<m;i++)
                for(int j=0;j<n;j++)
                    if(matrix[i][j]>FLAG)
                        FLAG=matrix[i][j];
            FLAG++;
            struct Direction dir[4];
            dir[0].x=0;dir[0].y=1;
            dir[1].x=1;dir[1].y=0;
            dir[2].x=0;dir[2].y=-1;
            dir[3].x=-1;dir[3].y=0;
            int cnt=0;
            int x=0;
            int y=-1;
            int diri=0;
            while(cnt<m*n)
            {
                while(x+dir[diri].x>=0 && x+dir[diri].x<m && y+dir[diri].y>=0 && y+dir[diri].y<n 
                    && matrix[x+dir[diri].x][y+dir[diri].y]!=FLAG)
                {
                    x=x+dir[diri].x;
                    y=y+dir[diri].y;
                    result.push_back(matrix[x][y]);
                    matrix[x][y]=FLAG;
                    cnt++;                
                }
                diri=(diri+1)%4;
            }
            return result;
        }
    }; 
  • 相关阅读:
    js封装一个哈希表
    js封装一个双链表
    js封装一个单链表
    js封装一个栈
    js封装一个优先级队列
    js封装一个队列
    微信小程序开发中自定义自适应头部导航栏
    Git的基本使用
    6位半数字万用表解释
    内存相关概念详解
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759396.html
Copyright © 2011-2022 走看看