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

總結(jié)

簡單粗暴的解法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容