public int[][] generateMatrix(int n) {

        if (n < 0) {
            return null;
        }

        int[][] res = new int[n][n];
        //start with value 1
        int start = 1, x = 0, y = 0;
        /**
         * after every loop, 2 numbers are filled into each row and column
         */
        for (int i = n; i > 0; i -= 2) {
            if (i == 1) {
                res[x][y] = start;
            } else {
                //[0][0] -> [0][n-2]
                for (int j = 0; j < i - 1; j++) {
                    res[x][y++] = start++;
                }
                //[0][n-1] -> [n-2][n-1]
                for (int j = 0; j < i - 1; j++) {
                    res[x++][y] = start++;
                }
                //[n-1][n-1] -> [n-1][1]
                for (int j = 0; j < i - 1; j++) {
                    res[x][y--] = start++;
                }
                //[n-1][0] -> [1][0]
                for (int j = 0; j < i - 1; j++) {
                    res[x--][y] = start++;
                }
                //after all, come to [0][0], then we need to go inner cycle
                x++;
                y++;
            }
        }
        return res;
    }