Files
C/DeitelC/Chapter7/maze7-25_2.c
2025-10-14 05:00:53 +03:00

77 lines
2.6 KiB
C

#include <stdio.h>
#define SIZE 12
// Function prototypes
void mazeTraverse(char maze[SIZE][SIZE], int row, int col, int direction);
void printMaze(const char maze[SIZE][SIZE]);
int main(void) {
char maze[SIZE][SIZE] = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', '.', '.', '.', '#', '.', '.', '.', '.', '.', '.', '#'},
{'.', '.', '#', '.', '#', '.', '#', '#', '#', '#', '.', '#'},
{'#', '#', '#', '.', '#', '.', '.', '.', '.', '#', '.', '#'},
{'#', '.', '.', '.', '.', '#', '#', '#', '.', '#', '.', '.'},
{'#', '#', '#', '#', '.', '#', '.', '#', '.', '#', '.', '#'},
{'#', '.', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#'},
{'#', '#', '.', '#', '.', '#', '.', '#', '.', '#', '.', '#'},
{'#', '.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#'},
{'#', '#', '#', '#', '#', '#', '.', '#', '#', '#', '.', '#'},
{'#', '.', '.', '.', '.', '.', '.', '#', '.', '.', '.', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
// Initial position and direction
int startRow = 2;
int startCol = 0;
int initialDirection = 0; // 0: Right, 1: Down, 2: Left, 3: Up
printf("The Maze:\n");
printMaze(maze);
printf("\nStarting Maze Traversal...\n\n");
mazeTraverse(maze, startRow, startCol, initialDirection);
return 0;
}
void mazeTraverse(char maze[SIZE][SIZE], int row, int col, int direction) {
// Moves: Right, Down, Left, Up
int moves[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int nextRow, nextCol;
maze[row][col] = 'X'; // Mark the current path
printMaze(maze);
printf("\n");
// Check for an exit
if ((row == 0 || row == SIZE - 1 || col == 0 || col == SIZE - 1) && !(row == 2 && col == 0)) {
printf("Exit found at (%d, %d)!\n", row, col);
return;
}
// Right-hand rule logic
for (int i = 0; i < 4; ++i) {
int nextDirection = (direction + i + 3) % 4; // Try right, then straight, then left
nextRow = row + moves[nextDirection][0];
nextCol = col + moves[nextDirection][1];
if (nextRow >= 0 && nextRow < SIZE && nextCol >= 0 && nextCol < SIZE && maze[nextRow][nextCol] != '#') {
mazeTraverse(maze, nextRow, nextCol, nextDirection);
return;
}
}
printf("Stuck at position (%d, %d)\n", row, col);
}
void printMaze(const char maze[SIZE][SIZE]) {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
printf("%c ", maze[i][j]);
}
printf("\n");
}
}