Very simple and concise solution in Java


  • 0
    Z
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            int upper=n-1, lower=0;
            int i=0, j=0;
    
            for(int k=1; k<=n*n; k++){
                matrix[i][j]=k;
                
                if(i==lower&&j<upper) j++;
                else if(j==upper&&i<upper) i++;
                else if(i==upper&&j>lower) j--;
                else if(j==lower&&n>lower) i--;
                
                if(i==lower&&j==lower){
                    i++;
                    j++;
                    lower++;
                    upper--;
                }
            }
            return matrix;
        }
    }

Log in to reply
 

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