Spiral Matrix II

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

Example 1:

Spiral Order Traversal of a Matrix
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

Please refer Spiral Matrix to read about Spiral Order Traversal of a Matrix

class Solution {
    public int[][] generateMatrix(int n) {
        
        int[][] matrix = new int[n][n];
        
        int left = 0;
        int top = 0;
        int right = n-1;
        int bottom = n-1;
       
        int k = 0;
        while( left <= right && top <= bottom){
            
            for(int i = top ; i <= right ; i++){
                matrix[top][i] = ++k;
            }
            top++;
            
            for(int i = top ; i <= bottom ; i++){
                matrix[i][right] = ++k;
            }
            right--;
            
            for(int i = right ; i >= left && top <= bottom ; i--){
                matrix[bottom][i] = ++k;
            }
            bottom--;
            
            for(int i = bottom ; i >= top && left <= right ; i--){
                matrix[i][left] = ++k;
            }
            left++;
        }
        return matrix;
    }
}

Categories: Array

Tagged as: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s