#include #include #include #if 1 #define FILENAME "sample.txt" #define WIDTH 8 #define HEIGHT 5 #else #define FILENAME "input.txt" #endif typedef struct node_t { char val; struct node_t *neighbours[4]; // up, down, left, right } node_t; node_t graph[WIDTH][HEIGHT]; void part1(); int char_index(char ch); int in_range(char a, char b); void print_graph(); void part1() { print_graph(); } void gen_graph(char table[WIDTH][HEIGHT]) { for(int i = 0; i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++) { for(int k = 0; k < 4; k++) graph[j][i].neighbours[k] = NULL; graph[j][i].val = table[j][i]; // up if(i > 0) if(in_range(table[j][i], table[j][i-1])) graph[j][i].neighbours[0] = &(graph[j][i-1]); // down if(i < HEIGHT - 1) { if(in_range(table[j][i], table[j][i+1])) graph[j][i].neighbours[1] = &(graph[j][i+1]); } // left if(j > 0) { if(in_range(table[i][j], table[j-1][i])) graph[j][i].neighbours[2] = &(graph[j-1][i]); } // right if(j < WIDTH - 1) { if(in_range(table[j][i], table[j+1][i])) graph[j][i].neighbours[3] = &(graph[j+1][i]); } } } void parse() { FILE *fp = fopen(FILENAME, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME); exit(1); } char table[WIDTH][HEIGHT] = {0}; char line[64]; for(int i = 0; fgets(line, sizeof(line), fp) != NULL && i < HEIGHT; i++) for(int j = 0; j < WIDTH; j++) table[j][i] = char_index(line[j]); gen_graph(table); fclose(fp); } int main(void) { parse(); part1(); return 0; } void print_graph() { for(int i = 0; i < HEIGHT; i++) { for(int j = 0; j < WIDTH; j++) { printf("(%2d %2d) %c -> ", j, i, graph[j][i].val + '`'); for(int k = 0; k < 4; k++) printf("%c ", (graph[j][i].neighbours[k] == NULL) ? '_' : graph[j][i].neighbours[k]->val + '`'); printf("\n"); } printf("\n"); } } int char_index(char ch) { if(ch == 'S') ch = '`'; else if(ch == 'E') ch = '{'; return ch - '`'; } int in_range(char a, char b) { if(a == b || a == b-1 || a == b+1) return 1; return 0; }