My java solution using two for loop


  • 0
    M
    public class Solution {
    public int[][] generateMatrix(int n) {
        
        int[][] m = new int[n][n];
        int count = 1;
        
        for(int i = 0; i < n/2 + 1; i++)    {
            int length = n - 1 - i;
            if(i - length >= 0)
                break;
            for(int j = i; j < length; j++)    {
                m[i][j] = count++;
            }
            for(int j = i; j < length; j++) {
                m[j][length] = count++;
            }
            for(int j = length; j >i; j--) {
                m[length][j] = count++;
            }
            for(int j = length; j >i ; j--) {
                m[j][i] = count++;
            }
        }
        if((n&1) == 1)
            m[n>>1][n>>1] = count++;
        return m;
    }
    

    }


Log in to reply
 

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