c++ 3ms simple explanation solution


  • 0
    N

    nr, nc mean the current row and current column.
    dirs mean the four direction that nr and nc should operation
    nStep mean how many step nr and nc should run.
    turns mean how many turn you have meet.
    for example,

    [1, 2, 3]
    [8, 9, 4]
    [7, 6, 5]
    

    The initial point is (0, 1) and you should turn right for 3 step, and turn down for 2 step, turn left for 2 step, turn up for 1 step, turn right for 1 step.

    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        vector<vector<int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        vector<int> nStep{n, n-1};
        int nr = 0, nc = -1;
        int turns = 0;
        for (int i=0; i<n*n;) {
            for (int j=0; j<nStep[turns%2]; j++,i++) {
                nr += dirs[turns%4][1];
                nc += dirs[turns%4][0];
                res[nr][nc] = i+1;
            }
            nStep[turns%2]--;
            turns++;
        }
        return res;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.