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) {
            vector<int> res;
            if(matrix.empty()) return res;
            int dx[] = {0,1,0,-1};
            int dy[] = {1,0,-1,0};
            int startx = 0,endx = matrix.size(), starty = 0,endy = matrix[0].size();
            int cnt = endx*endy, direction = 0, x =0 , y = 0;
            while(cnt > 0){
                res.push_back(matrix[x][y]);
                matrix[x][y] = -1;
                cnt--;
                int newx = x+dx[direction], newy=y+dy[direction];
                if(newx >=endx ||newx<startx || newy>=endy|| newy < starty) {
                    direction++;
                    if(direction%4 == 1) startx++;
                    else if(direction%4 == 2) endy--;
                    else if(direction%4 == 3) endx--;
                    else starty ++;
                }
                direction%=4;
                x+=dx[direction];y+=dy[direction];
            }
            return res;
        }
    };
  • 相关阅读:
    HAOI2015 树上染色
    HAOI2010 软件安装
    T2 Func<in T1,out T2>(T1 arg)
    事无巨细
    LitJson JavaScriptSerializer
    数据库操作
    jQuery:总体掌握
    sql一个题的解法分析讲解
    Javascript系列:总体理解
    c#
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3815353.html
Copyright © 2011-2022 走看看