Certainly! Below is a comprehensive Java program that creates a maze represented as a grid where each cell can be either open (path) or blocked (wall). The user provides the starting and ending points, and the program uses the Breadth-First Search (BFS) algorithm to find the shortest path from the start to the end.
Overview
-
Maze Representation: The maze is represented as a 2D grid using a 2D array. Each cell can either be:
-
User Input: The user provides the starting and ending coordinates.
-
Pathfinding Algorithm: BFS is employed to traverse the maze and find the shortest path.
-
Output: If a path exists, the program prints the maze with the path marked. Otherwise, it notifies that no path exists.
Complete Java Program
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class MazeSolver {
// Directions: up, down, left, right
private static final int[][] DIRECTIONS = {
{-1, 0}, // Up
{1, 0}, // Down
{0, -1}, // Left
{0, 1} // Right
};
// Function to perform BFS and find the shortest path
public static boolean bfs(int[][] maze, Point start, Point end, Point[][] parent) {
int rows = maze.length;
int cols = maze[0].length;
boolean[][] visited = new boolean[rows][cols];
Queue<Point> queue = new LinkedList<>();
queue.add(start);
visited[start.x][start.y] = true;
parent[start.x][start.y] = null;
while (!queue.isEmpty()) {
Point current = queue.remove();
// If we've reached the end, return true
if (current.x == end.x && current.y == end.y) {
return true;
}
// Explore neighbors
for (int[] dir : DIRECTIONS) {
int newX = current.x + dir[0];
int newY = current.y + dir[1];
// Check bounds and whether the cell is open and not visited
if (isValid(newX, newY, maze, visited)) {
queue.add(new Point(newX, newY));
visited[newX][newY] = true;
parent[newX][newY] = current;
}
}
}
// If end is not reachable
return false;
}
// Helper function to check if a cell is valid for traversal
public static boolean isValid(int x, int y, int[][] maze, boolean[][] visited) {
int rows = maze.length;
int cols = maze[0].length;
return (x >= 0 && x < rows) &&
(y >= 0 && y < cols) &&
(maze[x][y] == 0) &&
(!visited[x][y]);
}
// Function to reconstruct the path from end to start
public static void reconstructPath(Point[][] parent, Point start, Point end, char[][] mazePath) {
Point current = end;
while (current != null) {
if ((current.x != start.x || current.y != start.y)) {
mazePath[current.x][current.y] = '*'; // Mark the path
}
current = parent[current.x][current.y];
}
}
// Function to print the maze
public static void printMaze(char[][] maze) {
for (char[] row : maze) {
for (char cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
// Point class to represent coordinates in the maze
static class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Define the maze
// 0 = open path, 1 = wall
int[][] maze = {
{0, 1, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0},
{0, 1, 1, 1, 0, 1},
{0, 0, 0, 0, 0, 0}
};
int rows = maze.length;
int cols = maze[0].length;
System.out.println("Maze Layout (0 = Path, 1 = Wall):");
for (int[] row : maze) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
// Input start point
System.out.println("\nEnter starting point coordinates (row and column):");
int startX = scanner.nextInt();
int startY = scanner.nextInt();
// Input end point
System.out.println("Enter ending point coordinates (row and column):");
int endX = scanner.nextInt();
int endY = scanner.nextInt();
// Validate input
if (!isValid(startX, startY, maze, new boolean[rows][cols])) {
System.out.println("Invalid starting point.");
return;
}
if (!isValid(endX, endY, maze, new boolean[rows][cols])) {
System.out.println("Invalid ending point.");
return;
}
Point start = new Point(startX, startY);
Point end = new Point(endX, endY);
// Array to store the parent of each point for path reconstruction
Point[][] parent = new Point[rows][cols];
boolean pathFound = bfs(maze, start, end, parent);
if (pathFound) {
// Create a character maze for displaying the path
char[][] mazePath = new char[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mazePath[i][j] = (maze[i][j] == 1) ? '1' : '0';
}
}
// Reconstruct and mark the path in the maze
reconstructPath(parent, start, end, mazePath);
// Mark start and end
mazePath[start.x][start.y] = 'S';
mazePath[end.x][end.y] = 'E';
System.out.println("\nPath found:");
printMaze(mazePath);
} else {
System.out.println("No path exists from the starting point to the ending point.");
}
scanner.close();
}
}
Explanation
-
Classes and Data Structures:
Point: A simple class to represent a cell in the maze with x and y coordinates.
DIRECTIONS: An array representing the four possible movements (up, down, left, right).
-
BFS Implementation (bfs method):
- Initializes a
visited matrix to keep track of visited cells.
- Uses a
Queue to explore cells level by level.
- For each cell, explores all four possible directions.
- Uses a
parent matrix to keep track of the path.
-
Path Reconstruction (reconstructPath method):
- Starts from the end point and traces back to the start using the
parent matrix.
- Marks the path with
'*' in a character array representing the maze.
-
Input and Validation:
- The program allows the user to input the starting and ending points.
- Validates whether these points are within bounds and not walls.
-
Output:
- If a path is found, the maze is printed with the path marked by
'*', the start point marked by 'S', and the end point marked by 'E'.
- If no path exists, an appropriate message is displayed.
Sample Run
Maze Layout (0 = Path, 1 = Wall):
0 1 0 0 0 0
0 1 0 1 1 0
0 0 0 1 0 0
0 1 1 1 0 1
0 0 0 0 0 0
Enter starting point coordinates (row and column):
0 0
Enter ending point coordinates (row and column):
4 5
Path found:
S 1 0 0 0 0
* 1 0 1 1 0
* * * 1 0 0
0 1 1 1 0 1
0 0 0 0 0 E
Explanation of the Output:
S marks the starting point (0,0).
E marks the ending point (4,5).
* marks the cells that are part of the shortest path from S to E.
Customizing the Maze
You can modify the maze array in the main method to represent different maze configurations. Ensure that the starting and ending points are within the bounds of the maze and are not walls.
Example of a Different Maze:
int[][] maze = {
{0, 0, 0, 1, 0},
{1, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 1},
{0, 0, 0, 0, 0}
};
Conclusion
This Java program effectively models a maze and utilizes BFS to find the shortest path from a user-specified start to end point. BFS is chosen because it naturally explores all possible paths level by level, ensuring that the first time the end point is reached, the path taken is the shortest one. You can enhance this program further by allowing dynamic maze input, visual representations, or implementing additional features such as different movement rules or heuristics for pathfinding.