C++ simple solution state machine


  • 2
    K
    class Solution {
    public:
    vector<vector<int>> generateMatrix(int n) {
        
        if(n==0)return {};
        vector<vector <int>>matrix(n, vector<int>(n, 0));
        int i=0, j=0, counter=0, top=0, left=0, width=n, height=n;
        char way='r';
        while(counter++ != n * n){
            switch(way){
                case 'r':
                    matrix[i][j++]=counter;
                    if(j >=width){
                        j--;
                        i++;
                        top++;
                        way='d';
                    }
                    break;
                
                case 'd':
                    matrix[i++][j]=counter;
                    if(i >=height){
                        i--;
                        j--;
                        way='l';
                        width--;
                    }
                    break;
                case 'l':
                    matrix[i][j--]=counter;
                    if(j < left){
                        j++;
                        i--;
                        way='u';
                        height--;
                    }
                    break;
                case 'u':
                    matrix[i--][j]=counter;
                    if(i < top){
                        i++;
                        j++;
                        way='r';
                        left++;
                    }
                    break;
            }
        }
        
        return matrix;
    }
    

    };


  • 0

    It's easy to understand, but very slow.


  • 0
    M

    @kelseyzhou
    Thanks for the solution! I wish I had considered this approach.


Log in to reply
 

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