Straitforward C++ solution


  • 0
    R
    vector<vector<int>> generateMatrix(int n) {
        int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
        vector<vector<bool>> flag(n, vector<bool> (n));
        vector<vector<int> > res(n, vector<int> (n, 1));
        if(n == 0){
            return res;
        }
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++){
                flag[i][j] = false;
            }
        }
        int cnt = 1, dir_v = 0, dx, dy;
        int x = 0; int y = 0;
        res[x][y] = cnt;
        flag[0][0] = true;
        while(cnt < n*n){
            dx = dir[dir_v][0];
            dy = dir[dir_v][1];
            if(canWrite(x+dx, y+dy, n, flag)){
                cnt = cnt+1;
                x = x+dx;
                y = y+dy;
                res[x][y] = cnt;
                flag[x][y] = true;
            }
            else{
                dir_v = (dir_v+1)%4;
            }
        }
        return res;
    }
    bool canWrite(int x, int y, int n, vector<vector<bool>>& flag){
        if(x >= 0 && x < n && y >= 0 && y < n){
            if(flag[x][y] == false){
                return true;
            }
        }
        return false;
    }

Log in to reply
 

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