1. 程式人生 > 其它 >leetcode 螺旋矩陣II 中等

leetcode 螺旋矩陣II 中等

建議先做這個題:https://www.cnblogs.com/rookie-acmer/p/15072804.html

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n);
        for(auto &item : ans) item.resize(n, 0);
        solve(ans, 0, ans.size() - 1, 0, ans[0].size() - 1, 1);
        
return ans; } void solve(vector<vector<int>> &ans, int lef, int rig, int top, int bot, int n) { // left, right, top, bottom if(lef > rig || top > bot) return ; if(lef == rig) { for(int i = top; i <= bot; ++ i) ans[i][lef] = n ++;
return ; } if(top == bot) { for(int i = lef; i <= rig; ++ i) ans[top][i] = n ++; return ; } for(int i = lef; i <= rig; ++ i) ans[top][i] = n ++; for(int i = top + 1; i <= bot; ++ i) ans[i][rig] = n ++; for(int i = rig - 1
; i >= lef; -- i) ans[bot][i] = n ++; for(int i = bot - 1; i > top; -- i) ans[i][lef] = n ++; solve(ans, lef + 1, rig - 1, top + 1, bot - 1, n); } };