美文网首页
59. Spiral Matrix II/螺旋矩阵 II

59. Spiral Matrix II/螺旋矩阵 II

作者: 蜜糖_7474 | 来源:发表于2019-05-30 17:01 被阅读0次

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;
    }
};

总结

简单粗暴的解法

相关文章

网友评论

      本文标题:59. Spiral Matrix II/螺旋矩阵 II

      本文链接:https://www.haomeiwen.com/subject/tkwvtctx.html