Simple JAVA Solution


  • 0

    ...

    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        int count = 1, i = 0;
        for (; i < n>>1; i++) { // Spiral print
            for (int j = i; j < n-i-1; j++) ans[i][j] = count++;
            for (int j = i; j < n-i-1; j++) ans[j][n-i-1] = count++;
            for (int j = n-i-1; j > i; j--) ans[n-i-1][j] = count++;
            for (int j = n-i-1; j > i; j--) ans[j][i] = count++;
        }
        // Case when there is just one element in the innermost layer
        if (i<<1 == n-1) ans[i][i] = count;
        
        return ans;
    }
    

    ...


Log in to reply
 

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