59. Spiral Matrix II/螺旋矩阵 II

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

Example:

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

AC代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n);
        for (auto& row : ans) row.resize(n);
        int q = n * n + 1, l = 0, r = n - 1, u = 0, d = n - 1, cnt = 1, i = 0, j = 0;
        while (true) {
            while (j <= r) ans[i][j++] = cnt++;
            j--;
            i++;
            u++;
            if (cnt == q) break;
            while (i <= d) ans[i++][j] = cnt++;
            i--;
            j--;
            r--;
            if (cnt == q) break;
            while (j >= l) ans[i][j--] = cnt++;
            j++;
            i--;
            d--;
            if (cnt == q) break;
            while (i >= u) ans[i--][j] = cnt++;
            i++;
            j++;
            l++;
            if (cnt == q) break;
        }
        return ans;
    }
};

总结

简单粗暴的解法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容