public int[][] generateMatrix(int n) {
        if (n < 0) return null;
        int[][] result = new int[n][n];
        int cnt = 1;
        for (int i = 0; i < n / 2; ++i) {
            for (int j = i; j < n - i - 1; ++j) {
                result[i][j] = cnt++;
            }
            for (int j = i; j < n - i - 1; ++j) {
                result[j][n - i - 1] = cnt++;
            }
            for (int j = i; j < n - i - 1; ++j) {
                result[n - i - 1][n - j - 1] = cnt++;
            }
            for (int j = i; j < n - i - 1; ++j) {
                result[n - j - 1][i] = cnt++;
            }
        }
        if (n % 2 == 1) result[n / 2][n / 2] = cnt;
        return result;
    }