My Solution in Java: Easy to understand


  • 0
    M
    public int[][] generateMatrix(int n) {
      int[][] res=new int[n][n];
      if(n==0)
      return res;
      if(n==1)
      {
          res[0][0]=1;
          return res;
      }
      int count=1;
      for(int layer=0;layer<n/2;layer++){
           for(int i=layer;i<n-1-layer;i++){
                res[layer][i]=count++;
            }
            for(int i=layer;i<n-1-layer;i++){
                res[i][n-1-layer]=count++;
            }
            for(int i=n-1-layer;i>layer;i--){
                res[n-1-layer][i]=count++;
            }
            for(int i=n-1-layer;i>layer;i--){
                res[i][layer]=count++;
            }
      }
      
      if(n%2!=0)
      res[n/2][n/2]=count;
      
      return res;
    
    }

Log in to reply
 

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