Sharing my simple ++ solution (4ms)


  • 0
    T
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> result(n, vector<int>(n));
            if(n==0) // corner case
                return result;
                
            vector<vector<bool>> visited(n, vector<bool>(n, false));
            int i=0, j=0, direction=0, record=1;
            while(true)
            {
                result[i][j] = record;
                record++;
                visited[i][j]= true;
                int nexti=i, nextj=j;
                if(direction==0)
                    nextj++;
                else if(direction==1)
                    nexti++;
                else if(direction==2)
                    nextj--;
                else
                    nexti--;
                    
                if(nexti>=0 && nexti<n && nextj>=0 && nextj<n && visited[nexti][nextj]==false)
                {
                    i = nexti;
                    j = nextj;
                }
                else // direct
                {
                    direction = (direction+1)%4;
                    if(direction==0)
                        j++;
                    else if(direction==1)
                        i++;
                    else if(direction==2)
                        j--;
                    else
                        i--;
                        
                    if(i<0 || i>=n || j<0 || j>=n || visited[i][j]==true)
                        break;
                }
            }
            
            return result;
        }
    };

Log in to reply
 

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