Blogs Hub

Spiral Matrix II - Array - Medium - LeetCode - MiniTV

Spiral Matrix II - Array - Medium - LeetCode - मिनी टीवी

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

public class Solution {
    public int[][] GenerateMatrix(int n) {
        var result = new int[n][];
        for(int i=0;i<n;i++){
            result[i]=new int[n];    
        }
        
        int index = 1;
        int sx = 0;
        int sy = 0;
        int ex = n;
        int ey = n;
        while(sx < ex && sy < ey){
            for(int i=sy;i<ey;i++){
                result[sx][i]=index;
                index++;
            }
            sx++;
            
            for(int i=sx;i<ex;i++){
                result[i][ey-1]=index;
                index++;
            }
            ey--;
            
            if(sx<ex){
                for(int i=ey-1;i>=sy;i--){
                    result[ex-1][i]=index;
                    index++;
                }
                ex--;
            }
            
            if(sy<ey){
                for(int i=ex-1;i>=sx;i--){
                    result[i][sy]=index;
                    index++;
                }
                sy++;
            }
        }
        
        return result;
    }
}

Time Complexity: O(n^2)

Space Complexity: O(n^2)