#include #include #include #include #include "disjoint.h" typedef struct { int r; int c; int pixwidth; int *hwalls; int *vwalls; } Maze; void print_maze(Maze *m) { int i, j, k; int *pixmap; int r1, c1, si, pw; r1 = m->r+1; c1 = m->c+1; pw = m->pixwidth; pixmap = (int *) malloc(sizeof(int) * r1 * c1 * m->pixwidth * m->pixwidth); if (pixmap == NULL) { perror("malloc"); exit(1); } for (i = 0; i < r1 * c1 *m->pixwidth * m->pixwidth; i++) pixmap[i] = 255; for (i = 0; i < r1; i++) { for (j = 0; j < m->c; j++) { if (m->hwalls[i*m->c+j]) { si = (i * c1 * pw * pw) + pw * c1 * (pw/2+1) + j * pw + pw/2+1; for (k = 0; k < pw; k++) pixmap[si+k] = 0; } } } for (i = 0; i < m->r; i++) { for (j = 0; j < c1; j++) { if (m->vwalls[i*c1+j]) { si = (i * c1 * pw * pw) + pw * c1 * (pw/2+1) + j * pw + pw/2+1; for (k = 0; k < pw; k++) pixmap[si+k*c1*pw] = 0; } } } printf("P2\n%d %d\n255\n", c1 * m->pixwidth, r1 * m->pixwidth); for (i = 0; i < r1 * c1 *m->pixwidth * m->pixwidth; i++) printf("%d\n", pixmap[i]); exit(0); } main(int argc, char **argv) { Maze *m; int i, j; DisjointSet *ds; int e1, e2, s1, s2; if (argc != 4) { fprintf(stderr, "usage: maze r c pixwidth\n"); exit(1); } m = (Maze *) malloc(sizeof(Maze)); if (m == NULL) { perror("Malloc"); exit(1); } if (sscanf(argv[1], "%d", &(m->r)) != 1 || m->r <= 0) { fprintf(stderr, "bad r\n"); exit(1); } if (sscanf(argv[2], "%d", &(m->c)) != 1 || m->c <= 0) { fprintf(stderr, "bad c\n"); exit(1); } if (sscanf(argv[3], "%d", &(m->pixwidth)) != 1 || m->pixwidth <= 0 || m->pixwidth%2 == 0) { fprintf(stderr, "bad pixwidth (has to be odd, sorry)\n"); exit(1); } m->hwalls = (int *) malloc(sizeof(int) * (m->r+1) * m->c); if (m->hwalls == NULL) { perror("Malloc"); exit(1); } m->vwalls = (int *) malloc(sizeof(int) * (m->c+1) * m->r); if (m->vwalls == NULL) { perror("Malloc"); exit(1); } for (i = 0; i < (m->r+1) * m->c; i++) m->hwalls[i] = 1; for (i = 0; i < (m->c+1) * m->r; i++) m->vwalls[i] = 1; /* Delete the entry and exit walls */ m->hwalls[0] = 0; m->hwalls[m->r*m->c+m->c-1] = 0; ds = new_disjoint_set(m->r * m->c); for (i = 0; i < m->r*m->c; i++) disjoint_makeset(ds, i); srand48(time(0)); while (ds->nsets > 1) { if (lrand48()%2) { e1 = lrand48()%((m->r-1)*m->c); e2 = e1 + m->c; s1 = disjoint_find(ds, e1); s2 = disjoint_find(ds, e2); if (s1 != s2) { disjoint_union(ds, s1, s2); m->hwalls[e2] = 0; } } else { i = lrand48()%m->r; j = lrand48()%(m->c-1); e1 = i*m->c+j; e2 = e1+1; s1 = disjoint_find(ds, e1); s2 = disjoint_find(ds, e2); if (s1 != s2) { disjoint_union(ds, s1, s2); m->vwalls[i*(m->c+1)+j+1] = 0; } } } print_maze(m); }