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

LeetCode Spiral Matrix

时间:2015-03-13 12:46:26      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

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> ans;
        if (matrix.empty()) 
            return ans;

        int n = matrix.size(), m = matrix[0].size();
        int vis[1000][1000];
        memset(vis, 0, sizeof(vis));
        int dx[4] = {0, 1, 0, -1};
        int dy[4] = {1, 0, -1, 0};
        int dir = 0, x = 0, y = 0;
        for (int i = 0; i < n*m; i++) {
            ans.push_back(matrix[x][y]);
            vis[x][y] = 1;

            if (x+dx[dir] == n || x+dx[dir] < 0 || 
                y+dy[dir] == m || y+dy[dir] < 0 || 
                vis[x+dx[dir]][y+dy[dir]]) {
                    dir = (dir == 3) ? 0 : dir+1;
            }

            x += dx[dir];
            y += dy[dir];
        } 

        return ans;
    }
};



LeetCode Spiral Matrix

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/44239011

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