凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 59. Spiral Matrix II

分类:algorithm| 发布时间:2017-03-08 10:27:00


题目

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

题意

给定一个整数n, 生成一个以螺旋顺序填充 1 到 n 的平方的方阵。

解法

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> spiral(n, vector<int>(n));
        int u = 0, d = n - 1, l = 0, r = n - 1, k = 0;
        while (true) {
            // up
            for (int col = l; col <= r; col++) spiral[u][col] = ++k;
            if (++u > d) break;
            // right
            for (int row = u; row <= d; row++) spiral[row][r] = ++k;
            if (--r < l) break;
            // down
            for (int col = r; col >= l; col--) spiral[d][col] = ++k;
            if (--d < u) break;
            // left
            for (int row = d; row >= u; row--) spiral[row][l] = ++k;
            if (++l > r) break;
        }

        return spiral;
    }
};