Question
This code is recursive in nature. Please make it iterative in nature. public class Maze { final int N = 4; /* For printing the
This code is recursive in nature. Please make it iterative in nature.
public class Maze { final int N = 4; /* For printing the solution matrix sol[N][N] */ void printSolution(int sol[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + sol[i][j] + " "); System.out.println(); } } /* to check if whether direction x,y are valid*/ boolean isSafe(int maze[][], int x, int y) { // if (x,y outside ) return false return (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1); } boolean solveMaze(int maze[][]) { int sol[][] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if (solveMazeUtil(maze, 0, 0, sol) == false) { System.out.print("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* function to solve Maze problem*/ boolean solveMazeUtil(int maze[][], int x, int y, int sol[][]) { // if (x,y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x,y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol)) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol)) return true; /* Backtrack*/ sol[x][y] = 0; return false; } return false; } public static void main(String args[]) { Maze rat = new Maze(); int maze[][] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1} }; rat.solveMaze(maze); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started