Simple Solution

  • 0
        public static int[][] generateMatrix(int n) {
    		int[][] matrix = new int[n][n]; // By default filled with 0s
    		int count = 1, i=0, j=0;
    		while(count<=n*n) { // Generate n^2 elem and stop each while if bound reached or elem already generated (m[i][j]!=0)
    			while(j<n && matrix[i][j]==0) matrix[i][j++]=count++; // Go Right
    			j--;i++; // j-- to stay in bounds, i++ because first elem already filled
    			while(i<n && matrix[i][j]==0) matrix[i++][j]=count++; // Go Down
    			i--;j--; // i-- to stay in bounds, j-- because first elem already filled
    			while(j>=0 && matrix[i][j]==0) matrix[i][j--]=count++; // Go Left
    			j++;i--; // j++ to stay in bounds, i-- because first elem already filled
    			while(i>=0 && matrix[i][j]==0) matrix[i--][j]=count++; // Go Up
    			i++;j++; // i++ to stay in bounds, j++ because first elem already filled
    		return matrix;

    Code explained in comments

Log in to reply

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