Very simple solution using clockwise direction variable


  • 2
    L

    In case anyone is interested in a simple direction based solution...

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            
            vector<vector<int> > res(n, vector<int>(n, 0));
            
            if( n == 1 ) 
                res[0][0] = 1;
                
            if(n <= 1)    
                return res;
                
            int dx[] = {0, 1, 0,-1}, dy[] = {1, 0,-1, 0};
            int d = 0, i = 0, j = 0, v = 1;
            
            while(true){
                res[i][j] = v++;
                
                if( i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ])
                    d = (d+1)%4;
                
                i += dx[d], j += dy[d];
    
                if(res[i][j])
                    break;
            }
            return res;
        }
    };

  • 0
    S

    I think it is good answer with zero as unreached position


  • 0
    L

    Need to change if( i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ]) to:
    if(i+dx[d]<0 || j+dy[d]<0 || i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ])


  • 0
    L

    Not really. It's making a clockwise spiral like turn, never trying to reach the 0 boundary, given n > 1.


  • 0
    E

    The most outer bottom layer will reach out to 0 boundary.


Log in to reply
 

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