fork download
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5.  
  6. enum {
  7. W = 10, // width of maze
  8. H = 10 // height of maze
  9. };
  10.  
  11. enum {
  12. North,
  13. East,
  14. South,
  15. West,
  16. NDir
  17. };
  18.  
  19. char visited[H][W];
  20. char horz[H][W - 1]; // horizontal E-W paths in the maze
  21. char vert[H - 1][W]; // veritcal N-S paths in the maze
  22.  
  23. /*
  24.  * Fill dir with directions to unvisited cells, return count
  25.  */
  26. int adjacent(int dir[], int x, int y)
  27. {
  28. int ndir = 0;
  29.  
  30. if (y > 0 && visited[y - 1][x] == 0) dir[ndir++] = North;
  31. if (x < W - 1 && visited[y][x + 1] == 0) dir[ndir++] = East;
  32. if (y < H - 1 && visited[y + 1][x] == 0) dir[ndir++] = South;
  33. if (x > 0 && visited[y][x - 1] == 0) dir[ndir++] = West;
  34.  
  35. return ndir;
  36. }
  37.  
  38. /*
  39.  * Traverse cells depth first and create paths as you go
  40.  */
  41. void dfs(int x, int y)
  42. {
  43. int dir[NDir];
  44. int ndir;
  45.  
  46. visited[y][x] = 1;
  47.  
  48. ndir = adjacent(dir, x, y);
  49.  
  50. while (ndir) {
  51. int pick = rand() % ndir;
  52.  
  53. switch (dir[pick]) {
  54. case North: vert[y - 1][x] = 1; dfs(x, y - 1); break;
  55. case East: horz[y][x] = 1; dfs(x + 1, y); break;
  56. case South: vert[y][x] = 1; dfs(x, y + 1); break;
  57. case West: horz[y][x - 1] = 1; dfs(x - 1, y); break;
  58. }
  59.  
  60. ndir = adjacent(dir, x, y);
  61. }
  62. }
  63.  
  64. /*
  65.  * Print a map of the maze
  66.  */
  67. void map(void)
  68. {
  69. int i, j;
  70.  
  71. for (i = 0; i < W; i++) {
  72. putchar('_');
  73. putchar('_');
  74. }
  75.  
  76. putchar('\n');
  77.  
  78. for (j = 0; j < H; j++) {
  79. putchar('|');
  80.  
  81. for (i = 0; i < W; i++) {
  82. putchar(j < H - 1 && vert[j][i] ? ' ' : '_');
  83. putchar(i < W - 1 && horz[j][i] ? '_' : '|');
  84. }
  85.  
  86. putchar('\n');
  87. }
  88. }
  89.  
  90. int main()
  91. {
  92. srand(time(NULL));
  93.  
  94. dfs(0, 0);
  95. map();
  96.  
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
____________________
|____ | | _ _ | ___ |
| _ | |___| |___|__ |
| | | | _ | _ | _ |_|
| |_|___| | |___|__ |
|__ ___ | |_| ___ | |
| __|___|_____| | | |
| ___ | _ _ | ____| |
|__ |___| |_|__ | _ |
| | | | __| _ | | | |
|_____|_____|_____|_|