#include #include #include #include #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); }