59. Spiral Matrix II

来源:互联网 发布:农夫山泉瓶子尺寸数据 编辑:程序博客网 时间:2024/05/01 23:44

Problem

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

class Solution {public:    vector<vector<int>> generateMatrix(int n) {        int begin = 0, end = n - 1;        vector<vector<int> > ret (n, vector<int>(n, 0));        int num = 1;        while(begin < end) {            for(int i = begin; i < end; ++i) ret[begin][i] = num++;            for(int i = begin; i < end; ++i) ret[i][end] = num++;            for(int i = end; i > begin; --i) ret[end][i] = num++;            for(int i = end; i > begin; --i) ret[i][begin] = num++;            ++begin;            --end;        }        if(begin == end) {            ret[begin][begin] = num;        }        return ret;    }};
0 0
原创粉丝点击