59. Spiral Matrix II

    xiaoxiao2021-03-26  4

    1刷 跟之前那个蛇形一样。。。

    class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>>ve; vector<int>v; for(int i = 0; i < n; ++ i) v.push_back(0); for(int i = 0; i < n; ++ i) ve.push_back(v); int layer = (n + 1) / 2; int num = 1; int m = n; for(int i = 0; i < layer; i ++) { //row i: top-left --> top-right for(int j = i; j < n-i; j ++) ve[i][j] = num++; //col n-1-i: top-right --> bottom-right for(int j = i+1; j < m-i; j ++) ve[j][n-1-i] = num++; //row m-1-i: bottom-right --> bottom-left if(m-1-i > i) { for(int j = n-1-i-1; j >= i; j --) ve[m-1-i][j] = num++; } //col i: bottom-left --> top-left if(n-1-i > i) { for(int j = m-1-i-1; j > i; j --) ve[j][i] = num++; } } return ve; } };

    2刷 十分好,马上学习了上一题蛇形的做法,手动刷出了这一题,还要3刷练手练思维

    class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>>dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<vector<int>>ve(n, vector<int>(n, 0)); if(n == 0) return ve; vector<int>step{n, n - 1}; int num = 1; int index = 0; int ir = 0, ic = -1; while(step[index % 2]){ for(int i = 0; i < step[index % 2]; ++ i){ ir += dirs[index][0]; ic += dirs[index][1]; ve[ir][ic] = num++; } step[index % 2]--; index = (index + 1) % 4; } return ve; } };
    转载请注明原文地址: https://ju.6miu.com/read-650241.html

    最新回复(0)