#include <stdio.h>
-#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
-#include <uthash.h>
+#include <stdint.h>
-struct point { int x; int y; };
-struct entry { struct point key; UT_hash_handle hh; };
+struct point { uint8_t x; uint8_t y; };
+bool visited[102][102] = {0};
+int grid[102][102];
-bool havevisited(struct entry **visited, int x, int y)
+int basin(int x, int y)
{
- struct entry *e = NULL;
- struct point p;
- memset(&p, 0, sizeof(p));
- p.x = x;
- p.y = y;
- HASH_FIND(hh, *visited, &p, sizeof(struct point), e);
- return e;
-}
-
-void addvisited(struct entry **visited, struct point p)
-{
- struct entry *e = calloc(1, sizeof(struct entry));
- e->key = p;
- HASH_ADD(hh, *visited, key, sizeof(struct point), e);
-}
-
-int basin(struct entry **visited, int grid[102][102], int x, int y)
-{
- struct point stack[1000];
- memset(stack, 0, sizeof stack);
+ struct point stack[100];
int sp = 0;
int size = 0;
memset(&p, 0, sizeof p);
while(--sp >= 0) {
p = stack[sp];
- if (havevisited(visited, p.x, p.y))
+ if (visited[p.y][p.x])
continue;
- addvisited(visited, p);
+ visited[p.y][p.x] = true;
if (grid[p.y][p.x] == 9)
continue;
size++;
- if (!havevisited(visited, p.x+1, p.y))
+ if (!visited[p.y][p.x+1])
stack[sp++] = (struct point){.x=p.x+1, .y=p.y};
- if (!havevisited(visited, p.x-1, p.y))
+ if (!visited[p.y][p.x-1])
stack[sp++] = (struct point){.x=p.x-1, .y=p.y};
- if (!havevisited(visited, p.x, p.y+1))
+ if (!visited[p.y+1][p.x])
stack[sp++] = (struct point){.x=p.x, .y=p.y+1};
- if (!havevisited(visited, p.x, p.y-1))
+ if (!visited[p.y-1][p.x])
stack[sp++] = (struct point){.x=p.x, .y=p.y-1};
}
return size;
int main()
{
- int grid[102][102];
for (int i = 0; i<102; i++)
for (int j = 0; j<102; j++)
grid[i][j] = 9;
}
int tl[3] = {0};
- struct entry *visited = NULL;
for (int cy = 1; cy<y; cy++) {
for (int cx = 1; cx<maxx+1; cx++) {
- if (!havevisited(&visited, cx, cy)) {
- int s = basin(&visited, grid, cx, cy);
+ if (!visited[cy][cx]) {
+ int s = basin(cx, cy);
if (s >= tl[0]) {
tl[2] = tl[1];
tl[1] = tl[0];