public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int rowBegin = 0, rowEnd = n - 1, columnBegin = 0, columnEnd = n - 1;
        int num = 1;
        while (rowBegin <= rowEnd && columnBegin <= columnEnd) {
            // go left
            for (int i = columnBegin; i <= columnEnd; ++i) {
                result[rowBegin][i] = num++;
            }
            rowBegin++;
            // go down
            for (int i = rowBegin; i <= rowEnd; ++i) {
                result[i][columnEnd] = num++;
            }
            columnEnd--;
            if (rowBegin <= rowEnd) {
                for (int i = columnEnd; i >= columnBegin; --i) {
                    result[rowEnd][i] = num++;
                }
            }
            rowEnd--;
            if (columnBegin <= columnEnd) {
                for (int i = rowEnd; i >= rowBegin; --i) {
                    result[i][columnBegin] = num++;
                }
            }
            columnBegin++;
        }
        return result;
    }