Spiral Matrix II

 https://leetcode.com/problems/spiral-matrix-ii/

https://www.interviewbit.com/problems/spiral-order-matrix-ii/

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int top=0;
        int left=0;
        int bottom=n-1;
        int right=n-1;
        int direction=0;
        vector<vector<int>> ans(n,vector<int>(n));
        int count=1;
        while(left<=right && top<=bottom){
            if(direction==0){
                for(int i=left;i<=right;i++){
                    ans[top][i]=count;
                    count++;
                }
                top++;
            }
            else if(direction==1){
                for(int i=top;i<=bottom;i++){
                    ans[i][right]=count;
                    count++;
                }
                right--;
            }
            else if(direction==2){
                for(int i=right;i>=left;i--){
                    ans[bottom][i]=count;
                    count++;
                }
                bottom--;
            }
            else if(direction==3){
                for(int i=bottom;i>=top;i--){
                    ans[i][left]=count;
                    count++;
                }
                left++;
            }
            direction=(direction+1)%4;
            
        }
        return ans;
    }
};

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!