#include #include #include #define MAX_LEN 22 #define MAX_COORD 50 typedef struct { int x, y; } Point; typedef struct { Point path[MAX_LEN + 1]; int len; } Path; long long count_walks; int is_visited(Point *path, int len, int x, int y) { for (int i = 0; i < len; i++) { if (path[i].x == x && path[i].y == y) { return 1; } } return 0; } void step_to_coords(char step, int *dx, int *dy) { if (step == 'E') { *dx = 1; *dy = 0; } else if (step == 'N') { *dx = 0; *dy = 1; } else if (step == 'W') { *dx = -1; *dy = 0; } else if (step == 'S') { *dx = 0; *dy = -1; } } void dfs(Point *path, int len, int target_len) { if (len == target_len) { count_walks++; return; } Point current = path[len - 1]; char dirs[] = {'E', 'N', 'W', 'S'}; for (int i = 0; i < 4; i++) { int dx, dy; step_to_coords(dirs[i], &dx, &dy); int nx = current.x + dx; int ny = current.y + dy; if (!is_visited(path, len, nx, ny)) { path[len].x = nx; path[len].y = ny; dfs(path, len + 1, target_len); } } } int main(int argc, char *argv[]) { int target_len = 22; const char *prefix = ""; if (argc > 1) { target_len = atoi(argv[1]); } if (argc > 2) { prefix = argv[2]; } Point path[MAX_LEN + 1]; path[0].x = 0; path[0].y = 0; int len = 1; for (int i = 0; prefix[i]; i++) { int dx, dy; step_to_coords(prefix[i], &dx, &dy); path[len].x = path[len - 1].x + dx; path[len].y = path[len - 1].y + dy; len++; } count_walks = 0; dfs(path, len, target_len + 1); printf("%lld\n", count_walks); return 0; }