Advertisement
Guest User

well.c

a guest
Feb 23rd, 2018
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3.  
  4. #define MAX 256
  5.  
  6. void
  7. print(int *grid, int w, int h, int t, int s, int d)
  8. {
  9.     fputs("\x1b[H",stdout); // cursor to "home"
  10.     printf("t = %ds\n", t);
  11.     for (int y = 0; y < h; y++) {
  12.         for (int x = 0; x < w; x++) {
  13.             int i = y * w + x;
  14.             if (i == s)
  15.                 fputs("\x1b[93;1m",stdout);
  16.             else if (i == d)
  17.                 fputs("\x1b[94;1m",stdout);
  18.             printf("%-5.1f", grid[i] / (float)(w * h));
  19.             if (i == s || i == d)
  20.                 fputs("\x1b[0m",stdout);
  21.         }
  22.         putchar('\n');
  23.     }
  24. }
  25.  
  26. static void
  27. fill(int *grid, int w, int h, int i, char *visited)
  28. {
  29.     static const int d[] = {
  30.         +1, +0, -1, +0, +0, +1, +0, -1, +1, +1, +1, -1, -1, +1, -1, -1,
  31.     };
  32.     int x = i % w;
  33.     int y = i / w;
  34.     visited[i] = 1;
  35.     grid[i]++;
  36.     for (int j = 0; j < 8; j++) {
  37.         int tx = x + d[j * 2 + 0];
  38.         int ty = y + d[j * 2 + 1];
  39.         int ti = ty * w + tx;
  40.         if (tx >= 0 && tx < w && ty >= 0 && ty < h && !visited[ti]) {
  41.             if (grid[i] > grid[ti]) {
  42.                 grid[i]--;
  43.                 fill(grid, w, h, ti, visited);
  44.                 break;
  45.             }
  46.         }
  47.     }
  48. }
  49.  
  50. int
  51. main(void)
  52. {
  53.     int w, h, dst;
  54.     int grid[MAX];
  55.     scanf("%d%d", &w, &h);
  56.     for (int i = 0; i < w * h; i++)
  57.         scanf("%d", grid + i);
  58.     scanf("%d", &dst);
  59.  
  60.     int soff = 0;
  61.     int doff = 0;
  62.     int dval = (dst + 1) * w * h;
  63.     for (int i = 0; i < w * h; i++) {
  64.         if (grid[i] == 1)
  65.             soff = i;
  66.         if (grid[i] == dst)
  67.             doff = i;
  68.         grid[i] *= w * h;
  69.     }
  70.  
  71.     int t = 0;
  72.     fputs("\e[2J",stdout); // clear terminal
  73.     print(grid,w,h,0,soff,doff);usleep(250000);
  74.     for (; grid[doff] < dval; t++) {
  75.         for (int i = 0; i < w * h; i++) {
  76.             char visited[MAX] = {0};
  77.             fill(grid, w, h, soff, visited);
  78.         }
  79.         print(grid,w,h,t+1,soff,doff);
  80.         usleep(250000);
  81.     }
  82.     printf("%d\n", t);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement