59. Spiral Matrix II

Solution (C++):

vector<vector<int>> generateMatrix(int n) {
    if (!n)  return vector<vector<int>> {};
    vector<vector<int>> res(n, vector<int>(n, 0));
    vector<vector<int>> direc{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int direc_index = 0, val = 1;
    int x = 0, y = -1;      //initial position (0, -1)
    vector<int> steps{n, n-1};
    
    while (steps[direc_index%2]) {
        for (int i = 0; i < steps[direc_index%2]; ++i) {
            x += direc[direc_index][0];
            y += direc[direc_index][1];
            res[x][y] = val++;
        }
        steps[direc_index%2]--;
        direc_index = (direc_index + 1) % 4;
    }
    return res;
}

性能

Runtime: 0 ms  Memory Usage: 9.1 MB

posted @ 2020-02-11 19:34  littledy  阅读(56)  评论(0编辑  收藏  举报