LeetCode(57) SpiralMatrix II

题目如下:

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 ]
]


分析如下:

和上一道题目基本上一样的思路。


我的代码:

//5ms
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        int count = n/2;
        int offset = 0;
        int start = 1;
        vector<vector<int> > result(n, vector<int>(n,0));
        for (;offset < count; ++offset) {
            for (int i = offset; i < n - offset - 1; ++i, ++start) {
                result[offset][i] = start;
            }
            for (int i = offset; i < n - offset - 1; ++i, ++start) {
                result[i][n - offset - 1] = start;
            }
            for (int i = n - offset - 1; i > offset; --i, ++start) {
                result[n - offset - 1][i] = start;
            }
            for (int i = n - offset - 1; i > offset; --i, ++start) {
                result [i][offset] = start;
            }
        }
        if (n % 2 == 1)
            result[n/2][n/2] = start;
        return result;
    }
};



你可能感兴趣的:(LeetCode)