LeetCode 59. Spiral Matrix II

    xiaoxiao2021-08-29  99

    描述

    螺旋形遍历矩阵,把1~n^2的值依次序放在矩阵中

    解决

    遍历


    class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int st_r = 0, ed_r = n - 1; int st_c = 0, ed_c = n - 1; int cnt = 1; while (true) { //向右 for (int j = st_c; j <= ed_c; ++j) { res[st_r][j] = cnt++; } ++st_r; if (st_r > ed_r) break; //向下 for (int i = st_r; i <= ed_r; ++i) { res[i][ed_c] = cnt++; } --ed_c; if (ed_c < st_c) break; //向左 for (int j = ed_c; j >= st_c; --j) { res[ed_r][j] = cnt++; } --ed_r; if (ed_r < st_r) break; //向上 for (int i = ed_r; i >= st_r; --i) { res[i][st_c] = cnt++; } ++st_c; if (st_c > ed_c) break; } return res; } };
    转载请注明原文地址: https://ju.6miu.com/read-677314.html

    最新回复(0)