码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Spiral Matrix

时间:2014-07-07 14:22:37      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   art   cti   for   

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;
    }
};

 

Leetcode Spiral Matrix,布布扣,bubuko.com

Leetcode Spiral Matrix

标签:style   blog   color   art   cti   for   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3815353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!