fork download
  1. #include <stdio.h>
  2.  
  3. void printMaze(char maze[][100],
  4. int rows,
  5. int columns)
  6. {
  7. for (int row = 0; row < rows; ++row)
  8. {
  9. for (int column = 0; column < columns; ++column)
  10. {
  11. printf("%c ", maze[row][column]);
  12. }
  13.  
  14. puts("");
  15. }
  16.  
  17. puts("");
  18. }
  19.  
  20. int mazeTraverse(char maze[][100],
  21. int rows,
  22. int columns,
  23. int row,
  24. int column)
  25. {
  26. if (row < 0 || row >= rows ||
  27. column < 0 || column >= columns)
  28. {
  29. return 1;
  30. }
  31.  
  32. if (maze[row][column] != '.')
  33. {
  34. return 0;
  35. }
  36.  
  37. maze[row][column] = 'X';
  38.  
  39. if (mazeTraverse(maze,
  40. rows,
  41. columns,
  42. row,
  43. column + 1))
  44. {
  45. return 1;
  46. }
  47.  
  48. if (mazeTraverse(maze,
  49. rows,
  50. columns,
  51. row + 1,
  52. column))
  53. {
  54. return 1;
  55. }
  56.  
  57. if (mazeTraverse(maze,
  58. rows,
  59. columns,
  60. row,
  61. column - 1))
  62. {
  63. return 1;
  64. }
  65.  
  66. if (mazeTraverse(maze,
  67. rows,
  68. columns,
  69. row - 1,
  70. column))
  71. {
  72. return 1;
  73. }
  74.  
  75. maze[row][column] = '.';
  76.  
  77. return 0;
  78. }
  79.  
  80. int main(void)
  81. {
  82. int rows;
  83. int columns;
  84.  
  85. printf("Enter number of rows: ");
  86. scanf("%d", &rows);
  87.  
  88. printf("Enter number of columns: ");
  89. scanf("%d", &columns);
  90.  
  91. char maze[100][100];
  92.  
  93. printf("Enter the maze:\n");
  94.  
  95. for (int row = 0; row < rows; ++row)
  96. {
  97. for (int column = 0; column < columns; ++column)
  98. {
  99. scanf(" %c", &maze[row][column]);
  100. }
  101. }
  102.  
  103. printf("\nMaze before traversal:\n\n");
  104. printMaze(maze, rows, columns);
  105.  
  106. if (mazeTraverse(maze,
  107. rows,
  108. columns,
  109. 1,
  110. 1))
  111. {
  112. printf("The maze was solved.\n");
  113. }
  114. else
  115. {
  116. printf("No path was found.\n");
  117. }
  118.  
  119. printf("\nMaze after traversal:\n\n");
  120. printMaze(maze, rows, columns);
  121.  
  122. return 0;
  123. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Enter number of rows: Enter number of columns: Enter the maze:

Maze before traversal:


The maze was solved.

Maze after traversal: