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

LeetCode Spiral Matrix II

时间:2014-05-28 09:42:14      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

bubuko.com,布布扣
class Solution {
    public:
            vector<vector<int> > generateMatrix(int n) {
                vector<vector<int> > matrix;
                if (n < 1) return matrix;

                for (int i=0; i<n; i++) {
                    matrix.push_back(vector<int>(n, 0));
                }
                int left = 0, top = 0, right = n - 1, bottom = n - 1;
                int last = 1;
                while (left <= right && top <= bottom) {
                    last = circle_walk(last, left, top, right, bottom, matrix);
                    left++, top++, bottom--, right--;
                }
                return matrix;
            }

            int circle_walk(int start, int left, int top, int right, int bottom, vector<vector<int> >& map) {
                    int rows = 0;
                    if (map.size() < 1 || map[0].size() < 1) return start;
                            
                    // top row
                    for (int i=left; i<=right; i++) {
                        map[top][i] = start++;
                    }

                    // right col
                    for (int i=top+1; i<=bottom; i++) {
                       map[i][right] = start++;
                    }
                    
                    // bottom row
                    for (int i=right-1; bottom != top && i>=left; i--) {
                        map[bottom][i] = start++;
                    }

                    // left col
                    for (int i=bottom-1; left != right && i>top; i--) {
                        map[i][left] = start++;
                    }
                    return start;
            }
};
bubuko.com,布布扣

再水一发

LeetCode Spiral Matrix II,布布扣,bubuko.com

LeetCode Spiral Matrix II

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/lailailai/p/3755265.html

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