Java Solution - Clean and Simple


  • 0
    public static int[][] generateMatrix(int n) {
        int[][] m = new int[n][n];
        int k = 1;
        for (int i = 0; i < n; i++) {
            int increment = n - 1 - 2*i;
            for (int j = i; j < n - 1 - i; j++) {
                m[i][j] = k;
                m[j][n - 1 - i] = k+increment;
                m[n - 1 - i][n - 1 - j] = k+2*increment;
                m[n - 1 - j][i] = k+3*increment;
                k++;
            }
            k = k+3*increment;
        }
        if(n % 2 != 0) m[n/2][n/2] = n*n;//set the center if odd
        return m;
    }

Log in to reply
 

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