Maze Solver in C
It is a classical project. It is implemented by the use of graph traversal algorithm. It mainly finds the path from starting point to the end point.
Here, maze is represented as a 2D matrix. Walls are marked
as 1 and paths are marked as 0.
C implementation:
- · It starts from including header file.
- · First, the rows and columns are defined as 5.
- · Maze is initialized with values.
- · Visited value is created.
- · solveItMaze() function is used to solve the maze.
- · This function is used to visit all the rows and columns to find the path. The path starts from starting point to end point.
- · Main() function checks for path is not equal to 0,0.
- · Finally,the visited path is printed.
C Code:
#include <stdio.h>
#define M_ROWS 5
#define M_COLS 5
int maze[M_ROWS][M_COLS] = {
{0,1,0,0,0},
{0,1,0,1,0},
{0,0,0,1,0},
{1,1,0,0,0},
{0,0,0,1,0}
};
int visited[M_ROWS][M_COLS];
int solveItMaze(int x, int y) {
if (x == M_ROWS-1
&& y == M_COLS-1) {
printf("Exit found at (%d,%d)\n", x, y);
return 1;
}
if (x < 0 || y
< 0 || x >= M_ROWS || y >= M_COLS || maze[x][y] == 1 || visited[x][y])
return 0;
visited[x][y] = 1;
printf("Visiting (%d,%d)\n", x, y);
// Try all
directions
if
(solveItMaze(x+1, y) || solveItMaze(x-1, y) || solveItMaze(x, y+1) ||
solveItMaze(x, y-1))
return 1;
return 0;
}
int main() {
if
(!solveItMaze(0,0))
printf("No path found!\n");
return 0;
}
Output:
Visiting (0,0)
Visiting (1,0)
Visiting (2,0)
Visiting (2,1)
Visiting (2,2)
Visiting (3,2)
Visiting (4,2)
Visiting (4,1)
Visiting (4,0)
Visiting (3,3)
Visiting (3,4)
Exit found at (4,4)
Thus, the C program to Maze solver was implemented
successfully. Hope, this code is useful to you. Keep Coding!!!
Comments
Post a Comment