int isValidPath(int* path, int pathlen) { int x = 0; int y = 0; for(int i = 0; i < pathlen; i++) { switch(path[i]) { case 0: x++; y++; break; case 1: x++; y--; break; case 2: x-=2; break; default: return 0; } if(y < 0 || x < y) { return 0; } if(x == 0 && y == 0) { if(i != pathlen - 1) { return 0; } else { return 1; } } } return 0; } void incrementPath(int* path, int length) { for(int i = length - 1; i >= 0; i--) { if(path[i] == 2) { path[i] = 0; } else { path[i]++; return; } } } unsigned long long countPathsOfLen(int length) { if(length % 3 != 0 || length < 3) { return 0; } int path[length]; for(int i = 0; i < length; i++) { path[i] = 0; } long long iterationSearchLength = 1; unsigned long long count = 0; for(int i = 0; i < length; i++) { iterationSearchLength = iterationSearchLength * 3; } for(unsigned long long i = 0; i < iterationSearchLength; i++) { count += isValidPath(path, length); incrementPath(path, length); } return count; } unsigned long long a(int n) { return countPathsOfLen(n * 3); }