0059 - Spiral Matrix II

059 - Spiral Matrix II

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

Examples

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

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

Constraints

  • 1 <= n <= 20

Java Solution

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        
        if(n==0) return matrix;
        
        int rowStart = 0;
        int rowEnd = n-1;
        int columnStart = 0;
        int columnEnd = n-1;
        
        int value = 1;
        
        while(rowStart <= rowEnd && columnStart <= columnEnd) {
            for(int i = columnStart; i <= columnEnd; i++) {
                matrix[rowStart][i] = value++;        
            }
            rowStart++;
            
            for(int i = rowStart; i <= rowEnd; i++) {
                matrix[i][columnEnd] = value++;
            }
            columnEnd--;
            
            for(int i = columnEnd; i >= columnStart; i--) {
                if(rowStart <= rowEnd) matrix[rowEnd][i] = value++;
            }
            rowEnd--;
            
            for(int i = rowEnd; i >= rowStart; i--) {
                if(columnStart <= columnEnd) matrix[i][columnStart] = value++;
            }
            columnStart++;
        }   
        return matrix;
    }
}

Last updated