summaryrefslogtreecommitdiff
path: root/rotting-oranges-c/main.c
blob: f1a4caf70cb9d0108764b9e60dfe545bbc4084a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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);
}