0% found this document useful (0 votes)
75 views

Daa_report_final[1]

Uploaded by

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

Daa_report_final[1]

Uploaded by

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

TWISTS & TRACKS – THE MAZE SOLVER

A Mini Project Report submitted to


MOHAN BABU UNIVERSITY

in Partial Fulfillment of the Requirements for the Award of the degree of

BACHELOR OF
TECHNOLOGY IN
COMPUTER SCIENCE AND ENGINEERING (DATA SCIENCE)

Submitted by

SAMALA SUSMITHA REDDY (22102A030254)


THURIMELLA VENKATA SARAYU (22102A030266)
VUPPUTURI VAISHNAVI (22102A030274)

Under the Guidance of


Mrs . Chengamma Chitteti
Assistant Professor
Department of Data Science

Department of Data Science


SCHOOL OF COMPUTING
MOHAN BABU UNIVERSITY
Sree Sainath Nagar, Tirupati – 517 102, A.P., INDIA
2024-25
MOHAN BABU UNIVERSITY
Sree Sainath Nagar, Tirupati – 517 102, A.P., INDIA
2024-25

DEPARTMENT OF DATA SCIENCE


CERTIFICATE

This is to certify that the mini project report entitled

“TWISTS AND TRACKS – THE MAZE SOLVER”

is the Bonafide work done by

SAMALA SUSMITHA REDDY (22102A030254)


GTHURIMELLA VENKATA SARAYU (22102A030266)
VUPPUTURI VAISHNAVI (22102A030274)

in the Department of Data Science, and submitted to Mohan Babu


University, Tirupati in partial fulfillment of the requirements for the award
of the degree of Bachelor of Technology in Computer Science and
Engineering (Data Science) during the academic year 2024-2025. This
work has been carried out under my supervision. The results of this mini
project work have not been submitted to any university for the award of any
degree or diploma.

Guide: Head:

Mrs. Chengamma Chitteti Dr. P.K. Gupta


Assistant Professor Professor & Head
Dept. of Data Science Dept. of Data Science

INTERNAL EXAMINER EXTERNALEXAMINER


DEPARTMENT OF DATA SCIENCE

Vision
To become a Centre of Excellence in Data Science by imparting high quality
education through teaching, training and research

Mission

 To impart quality education in Computer Science and Engineering with


specializations in Data Science by disseminating knowledge through
contemporary curriculum, competent faculty and effective teaching-learning
methodologies.

 Nurture research, innovation and entrepreneurial skills among students and


faculty to contribute to the needs of industry and society.

 Inculcate professional attitude, ethical and social responsibilities for


prospective and promising Engineering profession.

 Encourage students to engage in life-long learning by creating awareness of


the contemporary developments in Computer Science and Engineering with
specialization in Data Science.
PROGRAM EDUCATIONAL OBJECTIVES
After few years of graduation, the graduates of B. Tech. CSE(DS) will:

PEO1. Pursue higher studies in Computer Science, Data science or


Management.
PEO2. Become successful entrepreneurs or be employed by acquiring
required skill sets in the domains of Data Science and allied areas.
PEO3. Exhibit progression and effective adaptation to technological
developments through life-long learning to address ever changing
industrial requirements and follow ethical attitude in professional
practice.

PROGRAM SPECIFIC OUTCOMES


On successful completion of the Program, the graduates of B. Tech. CSE(DS)
program will be able to:
PSO1. Apply appropriate data analytical techniques for building effective
decision-making systems.

PSO2. Develop intelligent systems using novel Machine Learning and


Artificial Intelligence techniques.

PSO3. Design and develop efficient software systems using modern tools,
techniques, and platforms to meet societal needs.
PSO4. Apply suitable tools and techniques to build secure distributed
systems.

PROGRAM OUTCOMES
On successful completion of the Program, the graduates of B.Tech. CSE (DS)
Program will be able to:

PO1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the
solution of complex engineering problems.

PO2. Problem analysis: Identify, formulate, review research literature, and


analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics, natural sciences, and
engineering sciences.

PO3. Design/development of solutions: Design solutions for complex


engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.

PO4. Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the professional engineering
practice.

PO7. Environment and sustainability: Understand the impact of the


professional engineering solutions in societal and environmental contexts,
and demonstrate the knowledge of, and need for sustainable
development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as


a member or leader in diverse teams, and in multidisciplinary settings.

PO10 Communication: Communicate effectively on complex engineering


. activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.

PO11 Project management and finance: Demonstrate knowledge and


. understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation
. and ability to engage in independent and life-long learning in the
broadest context of technological change.
DECLARATION

We hereby declare that this project report titled “Twists and tracks – The Maze Solver”

is a genuine work carried out by us, in B.Tech (Computer Science and Engineering (Data

Science)) degree course of Mohan Babu University, TIrupati and has not been submitted to

any other course or University for the award of any degree by us.

We declare that this written submission represents our ideas in our own words and where

others' ideas or words have been included, we have adequately cited and referenced the original

sources. We also declare that we have adhered to all principles of academic honesty and integrity

and have not misrepresented or fabricated or falsified any idea / data / fact / source in our

submission. We understand that any violation of the above will cause for disciplinary action by

the Institute and can also evoke penal action from the sources which have thus not been properly

cited or from whom proper permission has not been taken when needed.

Signature of the students

1.

2.

3.
ABSTRACT

Our travel Our project, "Twists & Tracks – The Maze Solver," aims to create an
intuitive and efficient platform for solving mazes using advanced algorithms like Depth-first
Search (DFS), Breadth-First Search (BFS), and A-star Search. The website utilizes these
algorithms to navigate and find optimal paths through complex maze structures. The platform is
designed to offer users a smooth and interactive experience, where they can easily input maze
configurations and visualize the solving process. By employing DFS, BFS, and A-star
algorithms, the system explores multiple solving strategies to demonstrate different approaches to
pathfinding and optimization. Built with HTML, CSS, and JavaScript, the interface is clean,
responsive, and user-friendly, making it accessible across all devices and screen sizes. The core
of the project leverages efficient algorithms to ensure fast processing and accurate results. The
interface is designed to be visually engaging, with clear step-by-step visualizations of the
algorithm's progress, providing a seamless user experience. JavaScript handles the logic for maze
generation, user interaction, and algorithm execution, making the process dynamic and
interactive. The system is optimized for performance, ensuring that users can quickly solve even
the most challenging mazes. Our goal with "Twists & Tracks" is to offer both an educational and
entertaining experience by showcasing the power of maze-solving algorithms while providing
users with an enjoyable journey through the world of computational problem-solving.

Keywords: Maze solver, Depth-first search, Breadth-first search, A-star search, Algorithm, Java.
TABLE OF CONTENTS

Title Page No.


ABSTRACT 1
CHAPTER 1: INTRODUCTION 2
INTRODUCTION 2
STATEMENT OF THE PROBLEM 3
OBJECTIVES 4
LIMITATIONS 4
CHAPTER 2: METHODOLOGY 5
CHAPTER 3: DESIGN 6
REQUIREMENTS 6
SYSTEM DESIGN 6
TECHNOLOGIES USED 7
CHAPTER 4: IMPLEMENTATION 8
CHAPTER: 5 PROPOSED SYSTEM ARCHITECTURE 9
CHAPTER 6: CODING AND RESULT 10
CODE 10
RESULT 31
CHAPTER 7: CONCLUSION AND FUTURE WORK 33
CONCLUSION 33
FUTURE WORK 33
TWISTS & TRACKS

CHAPTER- 1

INTRODUCTION

1.1 Introduction:

This report provides a detailed analysis of a maze solver project developed using advanced
algorithms like Depth-first Search (DFS), Breadth-first Search (BFS), and A-star Search. The
purpose of this project is to demonstrate the efficiency and effectiveness of these algorithms in
finding optimal paths through complex maze structures.

At Twists & Tracks, we understand that problem-solving is more than just finding a solution—
it’s about exploring various approaches, learning from each step, and improving efficiency. Our
maze solver showcases how these algorithms work in real-time to solve puzzles, offering users
the opportunity to see different strategies in action. Whether you're interested in the thorough
exploration of DFS, the level-wise solution of BFS, or the optimized pathfinding of A-star, our
platform allows users to engage with these methods in an interactive way.

Our goal is to make maze-solving both educational and engaging by providing a clear and
dynamic visualization of each algorithm’s process. By leveraging Java and interactive design,
we ensure that the experience is user-friendly and intuitive, enabling users to learn and
experiment with ease.

2
Department of CSSE
TWISTS & TRACKS

1.2 Problem Statement:

The fact that solving mazes efficiently can be complex due to the need for choosing the right
pathfinding algorithm creates challenges for developers and enthusiasts. The variety of
algorithms and their specific use cases make it difficult to select the best one for a given maze,
especially when considering factors like performance and optimality. This hinders developers'
ability to implement quick, reliable, and efficient maze-solving solutions. Therefore, there is a
need for a simple maze solver that incorporates multiple algorithms (Depth-First Search,
Breadth-First Search, and A-star Search) to provide different solving strategies and improve
accessibility for users. During the development of this project, we faced challenges with
optimizing the algorithms, handling large mazes, and ensuring smooth integration of various
features.

3
Department of CSSE
TWISTS & TRACKS

1.3 Objectives:

The main objective of the project is to provide users with an efficient and straightforward
maze-solving tool by implementing three popular algorithms—Depth-First Search, Breadth-
First Search, and A-star Search. The objectives are:

 Implement multiple pathfinding algorithms.

 Enhance algorithm comparison and selection.

 Provide optimal and alternative solutions.

 Ensure real-time maze solving.

 Ensure responsive design.

 Encourage tourism across states.

1.4 Limitations:

 Potential for slow performance in real-time scenarios

 Limited visualization for complex mazes

 Limited support for dynamic mazes

4
Department of CSSE
TWISTS & TRACKS

CHAPTER – 2

METHODOLOGY

The challenge in solving mazes efficiently arises from selecting the most suitable pathfinding
algorithm, as each algorithm has its strengths and limitations based on the maze's complexity and
size. Depth-First Search (DFS), Breadth-First Search (BFS), and A-star Search are three widely
used algorithms, each with different approaches to solving the maze. Therefore, the project aims
to implement these algorithms in a user-friendly interface, allowing users to select the best option
for their maze-solving needs. During the development of this project, we faced issues related to
algorithm optimization, managing memory usage for large mazes, and ensuring smooth
integration of all algorithms within the same system.

5
Department of CSSE
TWISTS & TRACKS

CHAPTER – 3
SYSTEM DESIGN

4.1 Requirements:

The user should have the appropriate version of windows.

• The system should have up to 1 GB ram minimum requirement for theapplication.

• Internet Connectivity is a must for this purpose.

4.2 System Design:

The maze solver application is designed with an intuitive interface for ease of use. The
following sections describe the key features and structure of the system:

HOME PAGE: The home page features an interactive maze creation tool, allowing users to
easily design custom mazes. It provides a simple navigation menu to select between different
algorithms (DFS, BFS, A-star) and view step-by-step visualizations of the maze-solving
process.

ALGORITHM SELECTION: Users can choose between Depth-First Search, Breadth-First


Search, or A-star Search for maze-solving. Each algorithm is explained briefly, and users can
observe its pathfinding approach through visual animations.

MAZE SOLVING PAGE: This page displays the generated maze and the selected algorithm’s
progress. It includes interactive controls to pause, resume, or restart the solving process, as well
as adjust maze difficulty and size.

RESPONSIVE DESIGN: The system is optimized for various screen sizes, ensuring a smooth
experience across desktops, tablets, and mobile devices. Layouts adapt to different devices,
allowing users to access features with ease.

6
Department of CSSE
TWISTS & TRACKS

4.3 Technologies used:

The maze solver application is developed using core technologies to provide an interactive and
efficient experience. The key technologies employed are:

JAVA: The main programming language used for implementing the maze-solving algorithms
(DFS, BFS, A-star), ensuring efficient and scalable performance.

JAVA 2D GRAPHICS: Java's 2D graphics library is employed for rendering the maze and
displaying the step-by-step algorithm execution, providing a clear visual representation.

THREADING: Java's threading capabilities are utilized to handle real-time algorithm execution,
allowing for smooth, stepwise solving of the maze without freezing the UI.

7
Department of CSSE
TWISTS & TRACKS

CHAPTER - 4

IMPLEMENTATION

The implementation of the project involves multiple stages to create a simple maze solver using
DFS, BFS, and A-star algorithms.

First, a thorough needs analysis was conducted to understand the requirements of the maze-
solving tool, its target audience, and the necessary algorithms. This analysis helped define the
objectives for providing efficient, optimal solutions to mazes. Once the requirements were clear,
the design phase began, focusing on creating an easy-to-use interface with clear visual elements,
a dynamic maze generator, and algorithm selector.

After finalizing the design, the development phase began using Java for implementing the
algorithms. The user interface was built using Swing, allowing for the visualization of the maze
and step-by-step solving process. The algorithms were optimized for performance, ensuring
quick and accurate results. Testing was performed to validate the algorithm implementations,
optimize execution time, and ensure the system works smoothly with varying maze sizes and
complexities.

8
Department of CSSE
TWISTS & TRACKS

CHAPTER-5
PROPOSED SYSTEM ARCHITECTURE

The system architecture for the maze solver follows a modular, layered approach. At the
presentation layer, the user interface is developed using Java Swing, providing a graphical
interface to display the maze and the solving process. The application layer handles the business
logic, which includes implementing the DFS, BFS, and A-star algorithms to solve the maze. The
algorithm logic is separated from the UI, ensuring better maintainability. The data access layer,
while minimal, handles maze data generation and manipulation, storing maze configurations
temporarily in memory. The proposed system architecture is designed to be efficient, easy to
expand, and capable of integrating new algorithms or features in the future.

9
Department of CSSE
TWISTS & TRACKS

CHAPTER-6
CODING ANALYSIS AND RESULTS

6.1 Code:

i. Main.java :

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

10
Department of CSSE
TWISTS & TRACKS

import javax.swing.JTextField;

public class Main extends Canvas implements Runnable, MouseListener {

private static Node start = null;


private static Node target = null;
private static JFrame frame;

private Node[][] nodeList;


private static Main runTimeMain;
private static Algorithm algorithm;

private final static int WIDTH = 1024;


private final static int HEIGHT = 768;

private final static int NODES_WIDTH = 28;


private final static int NODES_HEIGHT = 19;

public static void main(String[] args) {


frame = new JFrame(
"Maze Solver");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLayout(null);
Main m = new Main();
algorithm = new Algorithm();
// check
m.setBounds(0, 25, WIDTH, HEIGHT);
SetupMenu(frame);
runTimeMain = m;
// check
frame.add(m);
frame.setVisible(true);
m.start();

}
11
Department of CSSE
TWISTS & TRACKS

public static void SetupMenu(JFrame frame) {


JMenuBar bar = new JMenuBar();
bar.setBounds(0, 0, WIDTH, 25);
frame.add(bar);
JMenu fileMenu = new JMenu("File");
bar.add(fileMenu);
JMenu boardMenu = new JMenu("Board");
bar.add(boardMenu);
JMenu algorithmsMenu = new JMenu("Algorithms");
bar.add(algorithmsMenu);

JMenuItem saveMaze = new JMenuItem("Save Maze");


JMenuItem openMaze = new JMenuItem("Open Maze");
JMenuItem exit = new JMenuItem("Exit");

JMenuItem newGrid = new JMenuItem("New Board");


JMenuItem clearSearch = new JMenuItem("Clear Search Results");

JMenuItem bfsItem = new JMenuItem("Breadth-First Search");


JMenuItem dfsItem = new JMenuItem("Depth-First Search");
JMenuItem astarItem = new JMenuItem("A-star Search");
JMenuItem searchTime = new JMenuItem("Exploring time per Node");

openMaze.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {

try {
runTimeMain.openMaze();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
saveMaze.addActionListener(new ActionListener() {
12
Department of CSSE
TWISTS & TRACKS

public void actionPerformed(ActionEvent arg0) {


runTimeMain.clearSearchResults();
try {
runTimeMain.saveMaze();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
newGrid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
runTimeMain.createNodes(true);
}
});
clearSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
runTimeMain.clearSearchResults();
}
});

bfsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (runTimeMain.isMazeValid()) {
algorithm.bfs(runTimeMain.start, runTimeMain.target, runTimeMain.NODES_WIDTH,
runTimeMain.NODES_HEIGHT);
} else {
System.out.println("DIDNT LAUNCH");
}

}
13
Department of CSSE
TWISTS & TRACKS

});
dfsItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (runTimeMain.isMazeValid()) {
algorithm.dfs(runTimeMain.getStart());
} else {
System.out.println("DIDNT LAUNCH");
}

});
astarItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (runTimeMain.isMazeValid()) {
algorithm.Astar(runTimeMain.start, runTimeMain.target,
runTimeMain.NODES_WIDTH,
runTimeMain.NODES_HEIGHT);
} else {
System.out.println("DIDNT LAUNCH");
}

});
searchTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String input = JOptionPane.showInputDialog(null, "Enter a time it takes to search each
node in miliseconds(default = 100ms) ", "Search Time", JOptionPane.QUESTION_MESSAGE);
algorithm.setSearchTime(Integer.parseInt(input));
}
});

fileMenu.add(exit);
fileMenu.add(saveMaze);
fileMenu.add(openMaze);
14
Department of CSSE
TWISTS & TRACKS

boardMenu.add(newGrid);
boardMenu.add(clearSearch);
algorithmsMenu.add(dfsItem);
algorithmsMenu.add(bfsItem);
algorithmsMenu.add(astarItem);
algorithmsMenu.add(searchTime);

public void run() {


init();
while (true) {
// check
BufferStrategy bs = getBufferStrategy(); // check
if (bs == null) {
// check
createBufferStrategy(2);
continue;
}
// check
Graphics2D grap = (Graphics2D) bs.getDrawGraphics(); // check
render(grap);
bs.show();
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}

public void init() {


// check
requestFocus();
addMouseListener(this);
nodeList = new Node[NODES_WIDTH][NODES_HEIGHT];
15
Department of CSSE
TWISTS & TRACKS

createNodes(false);
setMazeDirections();
}
public void setMazeDirections() {
for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
Node up = null,down = null,left = null,right = null;
int u = j - 1;
int d = j + 1;
int l = i - 1;
int r = i + 1;

if(u >= 0) up = nodeList[i][u];


if(d < NODES_HEIGHT) down = nodeList[i][d];
if(l >= 0) left = nodeList[l][j];
if(r < NODES_WIDTH) right = nodeList[r][j];

nodeList[i][j].setDirections(left, right, up, down);


}
}
}
public void createNodes(boolean ref) {
for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
if(!ref) nodeList[i][j] = new Node(i, j).setX(15 + i * 35).setY(15 + j * 35);
nodeList[i][j].clearNode();
}
}
}

public void saveMaze() throws IOException {


JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showSaveDialog(frame);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
String ext = file.getAbsolutePath().endsWith(".maze") ? "" : ".maze";
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath() +
16
Department of CSSE
TWISTS & TRACKS

ext));
for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
if (nodeList[i][j].isWall()) {
outputWriter.write("1");
} else if (nodeList[i][j].isStart()) {
outputWriter.write("2");
} else if (nodeList[i][j].isEnd()) {
outputWriter.write("3");
} else {
outputWriter.write("0");
}
}
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}

public void openMaze() throws IOException {


JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(frame);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
String line = null;
for (int i = 0; i < NODES_WIDTH; i++) {
line = reader.readLine();
for (int j = 0; j < NODES_HEIGHT; j++) {

//nodeList[i][j].setColor(Color.BLACK);
int nodeType = Character.getNumericValue(line.charAt(j));
System.out.println("node is " + nodeType);
switch (nodeType) {
case 0:
17
Department of CSSE
TWISTS & TRACKS

nodeList[i][j].setColor(Color.LIGHT_GRAY);
break;
case 1:
nodeList[i][j].setColor(Color.BLACK);
break;

case 2:
nodeList[i][j].setColor(Color.GREEN);
start = nodeList[i][j];
break;
case 3:
nodeList[i][j].setColor(Color.RED);
target = nodeList[i][j];
break;
}
}

}
reader.close();
// System.out.println(stringMaze);
}
}

public void clearSearchResults() {


for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
if (nodeList[i][j].isSearched()) {
nodeList[i][j].clearNode();
}
}
}
if (isMazeValid()) {
target.setColor(Color.RED);
start.setColor(Color.GREEN);
}
}

18
Department of CSSE
TWISTS & TRACKS

public void render(Graphics2D g) {


g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
nodeList[i][j].render(g);
}
}
}

public void start() {


// check
new Thread(this).start();
}

public void mousePressed(MouseEvent e) {


Node clickedNode = getNodeAt(e.getX(), e.getY());
if (clickedNode == null)
return;

if (clickedNode.isWall()) {
clickedNode.clearNode();
return;
}

clickedNode.Clicked(e.getButton());

if (clickedNode.isEnd()) {
if (target != null) {
target.clearNode();
}
target = clickedNode;
} else if (clickedNode.isStart()) {

if (start != null) {
start.clearNode();
}
19
Department of CSSE
TWISTS & TRACKS

start = clickedNode;
}

public boolean isMazeValid() {


return target == null ? false : true && start == null ? false : true;
}

private Node getStart() {


for (int i = 0; i < nodeList.length; i++) {
for (int j = 0; j < nodeList[i].length; j++) {
if (nodeList[i][j].isStart()) {
return nodeList[i][j];
}
}
}
return null;
}

public Node getNodeAt(int x, int y) {


x -= 15;
x /= 35;
y -= 15;
y /= 35;

System.out.println(x + ":" + y);


if (x >= 0 && y >= 0 && x < nodeList.length && y < nodeList[x].length) {
return nodeList[x][y];
}
return null;
}

@Override
public void mouseClicked(MouseEvent arg0) {
}

20
Department of CSSE
TWISTS & TRACKS

@Override
public void mouseEntered(MouseEvent arg0) {
}

@Override
public void mouseExited(MouseEvent arg0) {
}

@Override
public void mouseReleased(MouseEvent arg0) {
}
}

21
Department of CSSE
TWISTS & TRACKS

ii. Algorithm.java :

import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

public class Algorithm {

private int searchtime = 100;

public int getSearchTime() {


return searchtime;
}
public void setSearchTime(int searchtime) {
this.searchtime = searchtime;
}

public void dfs(Node start) {


Stack<Node> nodes = new Stack<>();
nodes.push(start);

while (!nodes.empty()) {

Node curNode = nodes.pop();


if (!curNode.isEnd()) {

curNode.setColor(Color.ORANGE);
try {
Thread.sleep(searchtime);
} catch (Exception e) {
22
Department of CSSE
TWISTS & TRACKS

e.printStackTrace();
}
curNode.setColor(Color.BLUE);
for (Node adjacent : curNode.getNeighbours()) {
nodes.push(adjacent);
}

} else {
curNode.setColor(Color.MAGENTA);
break;
}
}

public void bfs(Node start, Node end, int graphWidth, int graphHeight) {
Queue<Node> queue = new LinkedList<>();
Node[][] prev = new Node[graphWidth][graphHeight];

queue.add(start);
while (!queue.isEmpty()) {

Node curNode = queue.poll();


if (curNode.isEnd()) {
curNode.setColor(Color.MAGENTA);
break;
}

if (!curNode.isSearched()) {
curNode.setColor(Color.ORANGE);
try {
Thread.sleep(searchtime);
} catch (Exception e) {
e.printStackTrace();
}
curNode.setColor(Color.BLUE);
for (Node adjacent : curNode.getNeighbours()) {
23
Department of CSSE
TWISTS & TRACKS

queue.add(adjacent);
prev[adjacent.getX()][adjacent.getY()] = curNode;

}
}
}

shortpath(prev, end);
}

private Node getLeastHeuristic(List<Node> nodes,Node end,Node start) {


if(!nodes.isEmpty()) {
Node leastH = nodes.get(0);
for(int i = 1; i < nodes.size();i++) {
double f1 = Node.distance(nodes.get(i), end);
double h1 = Node.distance(nodes.get(i), start);

double f2 = Node.distance(leastH, end);


double h2 = Node.distance(leastH, start);
if(f1 + h1 < f2 + h2) {
leastH = nodes.get(i);
}
}
return leastH;
}
return null;
}

private void shortpath(Node[][] prev, Node end) {


Node pathConstructor = end;
while(pathConstructor != null) {
pathConstructor = prev[pathConstructor.getX()][pathConstructor.getY()];

if(pathConstructor != null) {
pathConstructor.setColor(Color.ORANGE);
}
24
Department of CSSE
TWISTS & TRACKS

try {
Thread.sleep(searchtime);
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void Astar(Node start, Node targetNode, int graphWidth, int graphHeight) {
List<Node> openList = new ArrayList<Node>();
Node[][] prev = new Node[graphWidth][graphHeight];
openList.add(start);

while(!openList.isEmpty()) {

Node curNode = getLeastHeuristic(openList,targetNode,start);


openList.remove(curNode);

if(curNode.isEnd()) {
curNode.setColor(Color.MAGENTA);
break;
}
curNode.setColor(Color.ORANGE);
try {
Thread.sleep(searchtime);
} catch (Exception e) {
e.printStackTrace();
}
curNode.setColor(Color.BLUE);
for (Node adjacent : curNode.getNeighbours()) {
if(adjacent.isSearched()) {
continue;
}
double f1 = Node.distance(adjacent, targetNode);
double h1 = Node.distance(curNode, start);

double f2 = Node.distance(adjacent, targetNode);


25
Department of CSSE
TWISTS & TRACKS

double h2 = Node.distance(curNode, start);

if(!openList.contains(adjacent) || (f1 + h1 < f2 + h2)) {


prev[adjacent.getX()][adjacent.getY()] = curNode;
if(!openList.contains(adjacent)){
openList.add(adjacent);
}
}
}

}
shortpath(prev, targetNode);

26
Department of CSSE
TWISTS & TRACKS

iii. Node.java :

import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
import java.awt.Color;
import java.awt.Graphics2D;

public class Node {

private int Xpos;


private int Ypos;
private Color nodeColor = Color.LIGHT_GRAY;
private final int WIDTH = 35;
private final int HEIGHT = 35;
private Node left, right, up, down;

private double fcost;

public Node(int x, int y) {


Xpos = x;
Ypos = y;
}

public Node() {
}

public static double distance(Node a, Node b) {


double x = Math.pow(a.Xpos - b.Xpos, 2);
double y = Math.pow(a.Ypos - b.Ypos, 2);

return Math.sqrt(x + y);


}

public void render(Graphics2D g) {


g.setColor(Color.BLACK);
27
Department of CSSE
TWISTS & TRACKS

g.drawRect(Xpos, Ypos, WIDTH, HEIGHT);


g.setColor(nodeColor);
g.fillRect(Xpos + 1, Ypos + 1, WIDTH - 1, HEIGHT - 1);
}

public void Clicked(int buttonCode) {


System.out.println("called");
if (buttonCode == 1) {
// WALL
nodeColor = Color.BLACK;

}
if (buttonCode == 2) {
// START
nodeColor = Color.GREEN;

}
if (buttonCode == 3) {
// END
nodeColor = Color.RED;

}
if (buttonCode == 4) {
// CLEAR
clearNode();

}
}
public double getFCost() {
return this.fcost;
}

public void setFCost(double fcost) {


this.fcost = fcost;
}

public void setColor(Color c) {


28
Department of CSSE
TWISTS & TRACKS

nodeColor = c;
}

public Color getColor() {


return nodeColor;
}

public List<Node> getNeighbours() {


List<Node> neighbours = new ArrayList<>();
if (left != null && left.isPath())
neighbours.add(left);
if (down != null && down.isPath())
neighbours.add(down);
if (right != null && right.isPath())
neighbours.add(right);
if (up != null && up.isPath())
neighbours.add(up);

return neighbours;
}

public void setDirections(Node l, Node r, Node u, Node d) {


left = l;
right = r;
up = u;
down = d;
}

public void clearNode() {


nodeColor = Color.LIGHT_GRAY;
}

public int getX() {


return (Xpos - 15) / WIDTH;
}

public int getY() {


29
Department of CSSE
TWISTS & TRACKS

return (Ypos - 15) / HEIGHT;


}

public Node setX(int x) {


Xpos = x;
return this;
}

public Node setY(int y) {


Ypos = y;
return this;
}

public boolean isWall() {


return (nodeColor == Color.BLACK);
}

public boolean isStart() {


return (nodeColor == Color.GREEN);
}

public boolean isEnd() {


return (nodeColor == Color.RED);
}

public boolean isPath() {


return (nodeColor == Color.LIGHT_GRAY || nodeColor == Color.RED);
}

public boolean isSearched() {


return (nodeColor == Color.BLUE || nodeColor == Color.ORANGE);
}

30
Department of CSSE
TWISTS & TRACKS

6.2 Result:

i. The Maze Solver using Breadth-First Search Algorithm:


This page displays the maze solution using the Breadth-First Search (BFS) algorithm, showing
the shortest path from start to finish with a step-by-step traversal.

ii. The Maze Solver Using A – Star Search Algorithm:


This page displays the maze solution using the A-star search algorithm, showing the optimal path
from start to finish with step-by-step traversal.

31
Department of CSSE
TWISTS & TRACKS

iii. The Maze Solver using Depth-First Search Algorithm:


This page shows the maze solution using the DFS algorithm, displaying the path
from start to goal through depth-first exploration.

32
TWISTS & TRACKS

CHAPTER-7

CONCLUSION AND

FUTUREWORK

7.1 Conclusion:

The maze solver built using Depth-First Search, Breadth-First Search, and A-star algorithms
provides an efficient platform to solve mazes with varying complexities. Its interactive design and
multiple algorithm options allow users to understand different solving techniques, offering a
comprehensive and engaging experience for maze-solving enthusiasts.

7.2 Future Work:

This project offers several opportunities for future work and improvements. Potential areas include
optimizing the algorithms for faster performance, supporting more complex maze structures, and
adding visualization tools to track the search process. Implementing additional algorithms like
Dijkstra’s or Greedy Best-First Search could broaden the solution options. User customization
features, such as selecting grid sizes or maze difficulty levels, can improve the experience.
Additionally, integrating a mobile app or web interface for easy access, along with real-time maze
generation, can enhance user engagement. Introducing AI-based maze generation for more dynamic
and unpredictable puzzles would further enrich the project. Continuous testing and refining will
ensure optimal performance and accuracy.

33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy