diff options
author | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
---|---|---|
committer | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
commit | 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch) | |
tree | 0072cca328fe5adb2ed61004010228ff85e2164d /rotting-oranges-c/main.c |
Diffstat (limited to 'rotting-oranges-c/main.c')
-rw-r--r-- | rotting-oranges-c/main.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/rotting-oranges-c/main.c b/rotting-oranges-c/main.c new file mode 100644 index 0000000..f1a4caf --- /dev/null +++ b/rotting-oranges-c/main.c @@ -0,0 +1,62 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MAX(a,b) (((a)>(b))?(a):(b)) + +int orangesRotting(int** grid, int gridSize, int* gridColSize) { + int *grid2 = malloc(sizeof(int) * gridSize * *gridColSize); + memcpy(grid2, *grid, sizeof(int) * gridSize * *gridColSize); + printf("%d %d\n", gridSize, *gridColSize); + + for (int minutes = 0;; minutes++) { + for (int x = 0; x < gridSize; x++) { + for (int y = 0; y < *gridColSize; y++) { + printf("%d ", (*grid)[x * gridSize + y]); + if ( (*grid)[x * gridSize + y] != 2 ) continue; + + for (int dx = MAX(x-1,0); dx < MIN(x+2, gridSize); dx++) + if ((*grid)[dx * gridSize + y] == 1) (grid2)[dx * gridSize + y] = 2; + for (int dy = MAX(y-1, 0); dy < MIN(y+2, *gridColSize); dy++) + if ((*grid)[x * gridSize + dy] == 1) (grid2)[x * gridSize + dy] = 2; + } + printf("\n"); + } + + int finished = 1; + int same = 1; + for (size_t i = 0; i < gridSize * *gridColSize; i++) { + if ((*grid)[i] == 1) finished = 0; + same &= (*grid)[i] == grid2[i]; + } + + if (finished) return minutes; + + if (same) return -1; + int *temp = *grid; + *grid = grid2; + grid2 = temp; + memcpy(grid2, *grid, sizeof(int) * gridSize * *gridColSize); + } + + return 0; +} + +int main() { + int *test1 = malloc(sizeof(int) * 3 * 3); + int test[] = {2,1,1,1,1,0,0,1,1}; + memcpy(test1, test, sizeof(int) * 3 * 3); + + int gridColSize = 3; + + int result = orangesRotting(&test1, 3, &gridColSize); + + printf("is %d expeceted %d\n", result, 4); + + assert(result == 4); +} + + + |