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

		int[][] result = new int[n][n];
		int num = 1;
		int layer = n / 2;
		// here i is the layer number
		for (int i = 0; i < layer; i++) {
			// top
			for (int j = i; j < n - i; j++) {
				result[i][j] = num++;
			}
			// right
			for (int j = i + 1; j < n - i; j++) {
				result[j][n - i - 1] = num++;
			}
			// bottom
			for (int j = n - 1 - 1 - i; j >= i; j--) {
				result[n - 1 - i][j] = num++;
			}
			// left
			for (int j = n - i - 1 - 1; j > i; j--) {
				result[j][i] = num++;
			}
		}
		if (n % 2 != 0) {
			result[layer][layer] = num;
		}
		return result;

	}