Most concise Java solution


  • 1

    Anyone can read this code.

    public class Solution {
        public int[][] generateMatrix(int n) {
           int left=0, right=n-1;
           int up=0, down=n-1;
           int[][] m = new int[n][n];
           if(n==0) return m;
           int num=1;
           while(left<=right){
               for(int i=left;i<=right;++i){
                   m[up][i]=num++;
               }
               up++;
               for(int i=up;i<=down;++i){
                   m[i][right]=num++;
               }
               right--;
               for(int i=right;i>=left;--i){
                   m[down][i]=num++;
               }
               down--;
               for(int i=down;i>=up;--i){
                   m[i][left]=num++;
               }
               left++;
           }
           
           return m;
        }
    }

Log in to reply
 

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