Share my Java solution


  • 0
    F
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            int i=0, j=0, k=1,round=0;
            while(k<=n*n){
                while(j<n-round){
                    res[i][j] = k;
                    j++;
                    k++;
                }
                j-=1;
                i+=1;
                while(i<n-round){
                    res[i][j] = k;
                    i++;
                    k++;
                }
                i-=1;
                j-=1;
                while(j>=0+round){
                    res[i][j] = k;
                    j--;
                    k++;
                }
                j+=1;
                i-=1;
                round++;         //round increases one before go through the left edge
                while(i>=0+round){
                    res[i][j] = k;
                    i--;
                    k++;
                }
                i+=1;
                j+=1;
            }
            return res;
        }
    }
    

Log in to reply
 

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