0% found this document useful (0 votes)
19 views30 pages

Ds 1

Uploaded by

anishdubey590
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views30 pages

Ds 1

Uploaded by

anishdubey590
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

MAZE MASTER

Submitted by
Submitted to K.VARSHITHA
Ms.Vedavathi. K
Assistant Professor
( 23261A05G0 )
CSE, dept. K.NAVADEEP
( 23261A05G1 )
K.JAYANTH
( 23261A05G2 )
TABLE OF CONTENTS

• INTRODUCTION OF THE PROJECT 3


• KEY FEATURES OF MAZE SOLVER 4
• TECHNICAL APPROACH 5
• ALGORITHM 6
• TIME COMPLEXITY 8
• FLOW CHART 9
• IMPLEMENTATION OF THE CODE 10
• CODE SNIPPET 18
• OUTPUT 23
• APPLICATIONS 25
• CONCLUSION 26
• REFERENCES 27
• THANKYOU 28
INTRODUCTION OF THE PROJECT
● The Maze Solver project involves creating a program in C
language that can find a path through a maze using data structures
and algorithms. The maze is represented as a grid (2D array)
consisting of open spaces and walls. The objective of the project is
to determine a valid path from a designated start point to an end
point within the maze.
● To achieve this, the program utilizes algorithms like Depth-First
Search (DFS) or Breadth-First Search (BFS), along with data
structures such as stacks and queues. These data structures help
efficiently explore possible paths and backtrack when necessary.
● This project demonstrates the practical application of data
structures and algorithm concepts, such as pathfinding and graph
traversal, which are commonly used in fields like robotics, game
development, and artificial intelligence.
● By implementing this solution, we gain hands-on experience in
algorithm optimization, problem-solving, and C programming, as
well as an understanding of how to use data structures to solve
real-world problems.
KEY FEATURES OF MAZE SOLVER
 A Maze Solver is a program or algorithm designed to find a path through a maze from a starting point to
an ending point. The maze is typically represented as a grid or a 2D array consisting of walls and open
spaces. The goal of the maze solver is to navigate through the maze efficiently and determine a valid
route that leads to the exit, if one exists.
 Key Components of a Maze Solver:
• Maze Representation: The maze is usually represented as a 2D array or matrix.
• Start and End Points: The algorithm is given a start point (e.g., top-left corner) and an end point
(e.g., bottom-right corner) within the maze.
• Pathfinding Algorithms:
 Depth-First Search (DFS): Explores as far as possible along one branch before
backtracking.
 Breadth-First Search (BFS): Explores all neighboring nodes level by level, ensuring the
shortest path is found in unweighted mazes.
 A* : Uses heuristics to find the most efficient path, often used for weighted mazes.
• Data Structures: Stack (for DFS) or Queue (for BFS) to keep track of the nodes (positions) to be
explored. Visited Array to keep track of the cells that have already been checked.
 How a Maze Solver Works:
• Initialization: Load the maze into a 2D array. Define start and end points. Initialize necessary
data structures (e.g., stack, queue).
• Pathfinding: Start exploring from the starting point. Move in possible directions (up, down, left,
right) while avoiding walls and already visited cells. If a path reaches the end point, it is marked as
a solution. If all possible paths are explored without reaching the end, conclude that no solution
DEPTH FIRST SEARCH(DFS)

 DFS explores as deep as possible along each branch before backtracking.


 It uses a stack data structure, either explicitly or via recursion, to keep track of nodes to
be explored next.
 DFS starts at a given node and explores all its neighbours first before moving to the next
unvisited node.
 It can be implemented using recursion (implicitly using the call stack) or using an explicit
stack.
Steps:
1. Start at a given node (say start).
2. Mark the node as visited.
3. For each unvisited neighbour of the current node, visit it and recursively perform DFS.
4. Repeat this process until all reachable nodes from the starting node are visited.
ADT:
typedef struct DFS {
Graph *graph;
bool *visited; // An array to track visited vertices }
DFS;
BREADTH FIRST SEARCH
Breadth-First Search (BFS): Explores all neighboring nodes level by level, ensuring the shortest
path is found in unweighted mazes.
 BFS explores all neighbours at the present depth before moving on to nodes at the next depth
level.
 It uses a queue data structure to explore nodes level by level.
 BFS is often used to find the shortest path in an unweighted graph.
Steps:
1. Start at the given node and mark it as visited.
2. Add the starting node to the queue.
3. Dequeue a node from the queue, mark it as visited, and enqueue all its unvisited neighbours.
4. Repeat this process until all reachable nodes are visited.
ADT:
typedef struct BFS {
Graph *graph; bool *visited; // Array to track visited vertices
int *queue; // Queue for BFS traversal
int front; // Front of the queue
int rear; // Rear of the queue }
BFS;
TECHNICAL APPROACH

DATA STRUCTURE
● Language used: ALGORITHM USE CASE

2D Array Maze representation Stores maze layout

Stack Depth-First Search Finds any valid path

Queue Breadth-First Search Finds the shortest


path

Priority Queue A* Algorithm Finds optimal paths


using heuristics

Visited Array DFS,BFS Tracks visited cells

Graph Structures Dijkstra’s, A* Advanced


pathfinding in
weighted mazes
ALGORITHM
 INITIALIZATION:
•Initialize SDL (SDL_Init(SDL_INIT_VIDEO))
•Create a window (SDL_CreateWindow)
•Create a renderer (SDL_CreateRender)
•Define the maze layout as a 2D array (maze[MAZE_ROWS][MAZE_COLS])
•Set initial player position (playerX,playerY)

 START MAIN GAME LOOP:


• Input Handling:
1. Call SDL_PollEvent to check for events.
2. If the event type is SDL_QUIT, set running=false (exit the game).
3. If the event is a key press (SDL_KEYDOWN):
• Based on the key pressed (arrow keys), compute the new player's position
(newX,newY).
• Check if the new position is within bounds (ensure newX and newY are non-
negative and within maze bounds).
• Check if the new position is an open path (ensur maze[newY][newX] != 1 ).
• If valid, update playerX and playerY to newX and newY.
• RENDERING:
1. Clear the screen with SDL_RenderClear.
2. Loop through each tile in the maze.
• If the tile is a wall ( maze[y][x] == 1 ), draw a white rectangle.
• If the tile is a path ( maze[y][x] == 0 ), draw a black rectangle.
3. Draw the player at its current position as a green rectangle.
4. Present the render with SDL_RenderPresent.
• CHECH FOR GOAL:
1. Check if the player’s position matches the goal position( player == goalX && player ==
goalY ).
2. If the player reaches the goal, print a message (“You have reached the goal!”) and set
running = false to end the game.
• DELAY:
1. Add a delay using SDL_Delay(100) to control the frame rate ( or implementation more
sophisticated timing for smoother gameplay ).

 EXIT LOOP:
• Once the loop ends ( the player quits or reaches the goal ),destroy the render and window.
• Quit SDL (SDL_Duit).
TIME COMPLEXITY

DATA TIME SPACE


ALGORITHM STRUCTURE COMPLEXITY COMPLEXITY

Stack O(NXM) O(NXM)


DFS

BFS Queue O(NXM) O(NXM)

A* Priority Queue O(N X M log(N X M)) O(NXM)

Dijkstra’s Priority Queue O(N X M log(N X M)) O(NXM)


FLOW CHART

Set Player's Handle Input


Create Create Define Maze WHLE game
Initialize SDL initial (check
Window Renderer (2D array) is running:
position events)

Update IF new
Calculate
player position is
Clear the new position ELSE IF key Set running IF event is
position valid (not out
screen (newX, is pressed: to false SDL_QUIT:
(playerX, of bounds and
newY)
playerY) not a wall):

Draw player IF player


For each tile IF tile is a Draw white ELSE IF tile Draw black
at (playerX, reaches the
in maze: wall: rectangle is a path: rectangle
playerY) goal:

Cleanup SDL
resources Delay for Print "You've
Present the Set running
Quit SDL (Destroy frame rate
renderer to false
reached the
window and control goal!"
renderer)
IMPLEMENTATION OF THE CODE
1. HEADER FILES AND CONSTANTS

• #include <SDL2/SDL.h> :This includes the core SDL2 library, which provides functions for
handling graphics, events, and window management.
• #include <SDL2/SDL_main.h> :This includes the SDL2 main library, which is necessary for
initializing SDL and handling the entry point of the application (for certain platforms).
• #include <stdio.h> : Standard library for input and output functions, like printf for debugging.
• #include <stdbool.h>: Includes support for boolean data types (true, false), which is useful
for logic control.
2. CONSTANTS DEFINATIONS

• WINDOW_WIDTH and WINDOW_HEIGHT: Set the dimensions of the window where the
game will be displayed (640x480 pixels).
• TILE_SIZE: Defines the size of each tile (32x32 pixels), which makes it easy to manage the
grid-based maze layout.
• MAZE_ROWS and MAZE_COLS: Define the number of rows and columns in the maze (15
rows and 20 columns in this case).
3. MAZE LAYOUT

• maze[MAZE_ROWS][MAZE_COLS]: A 2D array representing the layout of the maze. Each


1 represents a wall, and each 0 represents a free path where the player can move.

4. PLAYER POSITION

• playerX and playerY: These variables track the player's position in the maze. The player
starts at the coordinates (1, 1), which is the second tile in the maze.
5. SDL INITIALIZATION

• SDL_Init(SDL_INIT_VIDEO): Initializes
SDL's video subsystem, which is required to
create windows and render graphics.

• SDL_CreateWindow: Creates the window


where the game will be displayed. It takes
parameters like window title, position,
dimensions, and flags (e.g.,
SDL_WINDOW_SHOWN for showing the
window).

• SDL_CreateRenderer: Creates a renderer that is responsible for rendering graphics to the


window. It uses hardware acceleration (SDL_RENDERER_ACCELERATED) and
synchronization (SDL_RENDERER_PRESENTVSYNC).

• The function returns true if all initializations are successful, otherwise returns false and
cleans up resources.
6. INPUT HANDLING
• SDL_PollEvent: Checks for events
such as user input. The function
returns true if an event is found and
processes it.

• SDL_KEYDOWN: When a key is


pressed, the function checks which
arrow key was pressed and updates
the player's position accordingly
(newX, newY).

• The function checks if the new


position is within the maze bounds
and if the new tile is not a wall
(maze[newY][newX] == 0). If it's valid,
it updates the player's coordinates.
7. RENDERING THE GAME
• SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255): This sets the draw color to
black (0, 0, 0) with full opacity (255). This color is used to clear the screen before
rendering new content.
• SDL_RenderClear(renderer): Clears the screen with the current draw color (black
in this case).

• Now, the maze is rendered:


• for (int y = 0; y < MAZE_ROWS; y++) and for (int x = 0; x < MAZE_COLS; x++):
• Loops through every row and column of the maze.
• if (maze[y][x] == 1): If the current position in the maze is a wall (value 1), the draw
color is set to white (255, 255, 255) for the walls.
• else: If the current position is a path (value 0), the draw color is set to black (0, 0,
0).
• SDL_Rect tile = { x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE };:
Defines the rectangle for each tile, ensuring each tile is rendered at the appropriate
position in the window. The TILE_SIZE determines the size of each tile (32x32
pixels).
• SDL_RenderFillRect(renderer, &tile);: Draws the rectangle (tile) on the screen.
• After rendering the maze tiles, the player is drawn:
• SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);: Sets the player color to green (0, 255, 0).
• SDL_Rect playerRect = { playerX * TILE_SIZE, playerY * TILE_SIZE, TILE_SIZE, TILE_SIZE };: Defines the rectangle for
the player's position, again scaling by TILE_SIZE for proper positioning.
• SDL_RenderFillRect(renderer, &playerRect);: Draws the player's rectangle on the screen.
• Finally, SDL_RenderPresent(renderer) updates the screen to show the rendered content.
8. MAIN GAME LOOP
• Game Initialization

1. SDL_Window *window = NULL; and


SDL_Renderer *renderer = NULL;:
Pointers for the SDL window and renderer.
2. if (!initSDL(&window, &renderer))
{ return 1; }: Initializes SDL and creates
the window/renderer. If any initialization
fails, the program exits with a return code
of 1.

• Main Game Loop

1. SDL_Event event;: Declares an event


structure to handle user inputs.
2. bool running = true;: A flag to control the
game loop. The game continues running
until running is set to false.
• Within the main loop:

1. handleInput(&event, &running);: Calls the handleInput function to process keyboard events


(e.g., arrow key presses).
2. render(renderer);: Calls the render function to redraw the maze and the player.
3. if (playerX == MAZE_COLS - 2 && playerY == MAZE_ROWS - 2): Checks if the player has
reached the goal, located at the bottom-right corner of the maze (MAZE_COLS - 2 and
MAZE_ROWS - 2 because the goal is inside the maze, not at the boundary).
• If the player reaches the goal, a success message is printed, and running is set to
false, ending the game loop.
4. SDL_Delay(100);: Pauses the game for 100 milliseconds to control the frame rate. This
ensures that the game doesn't run too fast, allowing smooth user input handling.

• Cleanup

1. SDL_DestroyRenderer(renderer); and SDL_DestroyWindow(window);: Cleanup by


destroying the renderer and window.
2. SDL_Quit();: Quits SDL and cleans up the resources used by the library.
• Return Code
1. return 0;: The program exits successfully with a return code of 0.
CODE SNIPPET
OUTPUT

FIG – 1 : Starting point of MAZE MASTER


FIG – 2 : Ending point of MAZE MASTER
Robotics
Navigation

Smart Video
Cities Games

APPLICATIONS

GPS and
Healthcare
Navigation

Network
Routing
CONCLUSION
 The maze solver program is an excellent demonstration of fundamental concepts in computer
science, including algorithm design, data structures, and problem-solving techniques. By
implementing various maze-solving algorithms like Depth-First Search (DFS), Breadth-First
Search (BFS), and A*, we gain practical insights into how different strategies can be used to
explore paths and find solutions efficiently.
a. Understanding of Algorithms: DFS is effective for exploring any possible path, while BFS
is more suitable for finding the shortest path in unweighted mazes. A* and Dijkstra's
algorithms are best for solving mazes with weighted paths, optimizing for both cost and
efficiency.
b. Practical Applications: Maze-solving techniques are not limited to puzzles but are widely
used in real-world applications such as robotics, game development, network routing, and
GPS navigation.
c. Efficiency Considerations: Choosing the right algorithm is crucial for performance,
especially with larger or more complex mazes. Understanding the time and space
complexities helps in making informed decisions.
d. Learning Outcomes: Implementing these algorithms in a language like C provides a
deeper understanding of low-level memory management and optimization. This project
serves as a strong foundation for exploring more advanced topics in computer science, such
as artificial intelligence and pathfinding in dynamic environments.
 The maze solver project not only enhances your coding skills but also equips you with essential
REFERENCES

● https://www.youtube.com/watch?v=zalhUp4ms6c
● https://github.com/edusporto/maze-solver-c/blob/master/maze-solver.c
● https://github.com/edusporto/maze-solver-c
THANK YOU

You might also like