public static int[][] generateMatrix(int n) {
    	int[][] res = new int[n][n];
    	int start = 1;
    	int istart = 0, iend = n;
    	int jstart = 0, jend = n;
    	while (start <= (n * n)) {
    		for (int j = jstart; j < jend; j++) {
    			res[istart][j] = start;
    			start = start + 1;
    		}
    		for (int i = istart + 1; i < iend; i++) {
    			res[i][jend - 1] = start;
    			start = start + 1;
    		}
    		for (int j = jend - 2; j >= jstart; j--) {
    			res[iend - 1][j] = start;
    			start = start + 1;
    		}
    		for (int i = iend - 2; i >= istart + 1; i--) {
    			res[i][jstart] = start;
    			start = start + 1;
    		}
    		istart = istart + 1;
    		iend = iend - 1;
    		jstart = jstart + 1;
    		jend = jend - 1;
    	}
        return res;
    }