Open In App

Find paths from corner cell to middle cell in maze

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a square maze containing positive numbers, find all paths from a corner cell (any of the extreme four corners) to the middle cell. We can move exactly n steps from a cell in 4 directions i.e. North, East, West and South where n is value of the cell

We can move to mat[i+n][j], mat[i-n][j], mat[i][j+n], and mat[i][j-n] from a cell mat[i][j] where n is value of mat[i][j].

Example

Input:  9 x 9 maze
[ 3, 5, 4, 4, 7, 3, 4, 6, 3 ]
[ 6, 7, 5, 6, 6, 2, 6, 6, 2 ]
[ 3, 3, 4, 3, 2, 5, 4, 7, 2 ]
[ 6, 5, 5, 1, 2, 3, 6, 5, 6 ]
[ 3, 3, 4, 3, 0, 1, 4, 3, 4 ]
[ 3, 5, 4, 3, 2, 2, 3, 3, 5 ]
[ 3, 5, 4, 3, 2, 6, 4, 4, 3 ]
[ 3, 5, 1, 3, 7, 5, 3, 6, 4 ]
[ 6, 2, 4, 3, 4, 5, 4, 5, 1 ]

Output:
(0, 0) -> (0, 3) -> (0, 7) -> 
(6, 7) -> (6, 3) -> (3, 3) -> 
(3, 4) -> (5, 4) -> (5, 2) -> 
(1, 2) -> (1, 7) -> (7, 7) ->
(7, 1) -> (2, 1) -> (2, 4) -> 
(4, 4) -> MID

The idea is to use backtracking. We start with each corner cell of the maze and recursively checks if it leads to the solution or not. Following is the Backtracking algorithm –
If destination is reached

  1. print the path

Else

  1. Mark current cell as visited and add it to path array.
  2. Move forward in all 4 allowed directions and recursively check if any of them leads to a solution.
  3. If none of the above solutions work then mark this cell as not visited and remove it from path array.

Below is the implementation of the above approach:

C++




// C++ program to find a path from corner cell to
// middle cell in maze containing positive numbers
#include <bits/stdc++.h>
using namespace std;
 
// Rows and columns in given maze
#define N 9
 
// check whether given cell is a valid cell or not.
bool isValid(set<pair<int, int> > visited,
             pair<int, int> pt)
{
    // check if cell is not visited yet to
    // avoid cycles (infinite loop) and its
    // row and column number is in range
    return (pt.first >= 0) && (pt.first  < N) &&
           (pt.second >= 0) && (pt.second < N) &&
           (visited.find(pt) == visited.end());
}
 
// Function to print path from source to middle coordinate
void printPath(list<pair<int, int> > path)
{
    for (auto it = path.begin(); it != path.end(); it++)
        cout << "(" << it->first << ", "
             << it->second << ") -> ";
 
    cout << "MID" << endl << endl;
}
 
// For searching in all 4 direction
int row[] = {-1, 1, 0, 0};
int col[] = { 0, 0, -1, 1};
 
// Coordinates of 4 corners of matrix
int _row[] = { 0, 0, N-1, N-1};
int _col[] = { 0, N-1, 0, N-1};
 
void findPathInMazeUtil(int maze[N][N],
                list<pair<int, int> > &path,
                set<pair<int, int> > &visited,
                pair<int, int> &curr)
{
    // If we have reached the destination cell.
    // print the complete path
    if (curr.first == N / 2 && curr.second == N / 2)
    {
        printPath(path);
        return;
    }
 
    // consider each direction
    for (int i = 0; i < 4; ++i)
    {
        // get value of current cell
        int n = maze[curr.first][curr.second];
 
        // We can move N cells in either of 4 directions
        int x = curr.first + row[i]*n;
        int y = curr.second + col[i]*n;
 
        // Constructs a pair object with its first element
        // set to x and its second element set to y
        pair<int, int> next = make_pair(x, y);
 
        // if valid pair
        if (isValid(visited, next))
        {
            // mark cell as visited
            visited.insert(next);
 
            // add cell to current path
            path.push_back(next);
 
            // recurse for next cell
            findPathInMazeUtil(maze, path, visited, next);
 
            // backtrack
            path.pop_back();
             
            // remove cell from current path
            visited.erase(next);
        }
    }
}
 
// Function to find a path from corner cell to
// middle cell in maze containing positive numbers
void findPathInMaze(int maze[N][N])
{
    // list to store complete path
    // from source to destination
    list<pair<int, int> > path;
 
    // to store cells already visited in current path
    set<pair<int, int> > visited;
 
    // Consider each corners as the starting
    // point and search in maze
    for (int i = 0; i < 4; ++i)
    {
        int x = _row[i];
        int y = _col[i];
 
        // Constructs a pair object
        pair<int, int> pt = make_pair(x, y);
 
        // mark cell as visited
        visited.insert(pt);
 
        // add cell to current path
        path.push_back(pt);
 
        findPathInMazeUtil(maze, path, visited, pt);
 
        // backtrack
        path.pop_back();
 
        // remove cell from current path
        visited.erase(pt);
    }
}
 
int main()
{
    int maze[N][N] =
    {
        { 3, 5, 4, 4, 7, 3, 4, 6, 3 },
        { 6, 7, 5, 6, 6, 2, 6, 6, 2 },
        { 3, 3, 4, 3, 2, 5, 4, 7, 2 },
        { 6, 5, 5, 1, 2, 3, 6, 5, 6 },
        { 3, 3, 4, 3, 0, 1, 4, 3, 4 },
        { 3, 5, 4, 3, 2, 2, 3, 3, 5 },
        { 3, 5, 4, 3, 2, 6, 4, 4, 3 },
        { 3, 5, 1, 3, 7, 5, 3, 6, 4 },
        { 6, 2, 4, 3, 4, 5, 4, 5, 1 }
    };
 
    findPathInMaze(maze);
 
    return 0;
}


Python3




# Python program to find a path from corner cell to
# middle cell in maze containing positive numbers
 
# Rows and columns in given maze
N = 9
 
# check whether given cell is a valid cell or not.
def isValid(visited, pt):
    # check if cell is not visited yet to
    # avoid cycles (infinite loop) and its
    # row and column number is in range
    return (pt[0] >= 0) and (pt[0] < N) and (pt[1] >= 0) and (pt[1] < N) and (pt not in visited)
 
# Function to print path from source to middle coordinate
def printPath(path):
    for i in path:
        print("({}, {}) -> ".format(i[0], i[1]), end="")
    print("MID")
    print()
 
# For searching in all 4 direction
row = [-1, 1, 0, 0]
col = [0, 0, -1, 1]
 
# Coordinates of 4 corners of matrix
_row = [0, 0, N-1, N-1]
_col = [0, N-1, 0, N-1]
 
def findPathInMazeUtil(maze, path, visited, curr):
    # If we have reached the destination cell.
    # print the complete path
    if curr[0] == N // 2 and curr[1] == N // 2:
        printPath(path)
        return
    # consider each direction
    for i in range(4):
        # get value of current cell
        n = maze[curr[0]][curr[1]]
        # We can move N cells in either of 4 directions
        x = curr[0] + row[i]*n
        y = curr[1] + col[i]*n
        next = (x, y)
        # if valid pair
        if isValid(visited, next):
            # mark cell as visited
            visited.append(next)
            # add cell to current path
            path.append(next)
            # recurse for next cell
            findPathInMazeUtil(maze, path, visited, next)
            # backtrack
            # remove cell from current path
            path.pop()
            visited.remove(next)
 
# Function to find a path from corner cell to
# middle cell in maze containing positive numbers
def findPathInMaze(maze):
    # list to store complete path
    # from source to destination
    path = []
    # to store cells already visited in current path
    visited = []
 
    # Consider each corners as the starting
    # point and search in maze
    for i in range(4):
        x = _row[i]
        y = _col[i]
        pt = (x, y)
        # mark cell as visited
        visited.append(pt)
        # add cell to current path
        path.append(pt)
        findPathInMazeUtil(maze, path, visited, pt)
        # backtrack
        # remove cell from current path
        path.pop()
        visited.remove(pt)
 
if __name__ == "__main__":
    maze = [
        [3, 5, 4, 4, 7, 3, 4, 6, 3],
        [6, 7, 5, 6, 6, 2, 6, 6, 2],
        [3, 3, 4, 3, 2, 5, 4, 7, 2],
        [6, 5, 5, 1, 2, 3, 6, 5, 6],
        [3, 3, 4, 3, 0, 1, 4, 3, 4],
        [3, 5, 4, 3, 2, 2, 3, 3, 5],
        [3, 5, 4, 3, 2, 6, 4, 4, 3],
        [3, 5, 1, 3, 7, 5, 3, 6, 4],
        [6, 2, 4, 3, 4, 5, 4, 5, 1]
    ]
 
    findPathInMaze(maze)
 
# This code is contributed by Vikram_Shirsat


C#




using System;
using System.Collections.Generic;
 
namespace MazePathFinder
{
    class Program
    {
        // Rows and columns in given maze
        const int N = 9;
 
        // check whether given cell is a valid cell or not.
        static bool IsValid(List<(int, int)> visited, (int, int) pt)
        {
            // check if cell is not visited yet to
            // avoid cycles (infinite loop) and its
            // row and column number is in range
            return (pt.Item1 >= 0) && (pt.Item1 < N) && (pt.Item2 >= 0) && (pt.Item2 < N) && (!visited.Contains(pt));
        }
 
        // Function to print path from source to middle coordinate
        static void PrintPath(List<(int, int)> path)
        {
            foreach (var i in path)
            {
                Console.Write($"({i.Item1}, {i.Item2}) -> ");
            }
            Console.WriteLine("MID");
            Console.WriteLine();
        }
 
        // For searching in all 4 direction
        static int[] row = { -1, 1, 0, 0 };
        static int[] col = { 0, 0, -1, 1 };
 
        // Coordinates of 4 corners of matrix
        static int[] _row = { 0, 0, N - 1, N - 1 };
        static int[] _col = { 0, N - 1, 0, N - 1 };
 
        static void FindPathInMazeUtil(int[][] maze, List<(int, int)> path, List<(int, int)> visited, (int, int) curr)
        {
            // If we have reached the destination cell.
            // print the complete path
            if (curr.Item1 == N / 2 && curr.Item2 == N / 2)
            {
                PrintPath(path);
                return;
            }
            // consider each direction
            for (int i = 0; i < 4; i++)
            {
                // get value of current cell
                int n = maze[curr.Item1][curr.Item2];
                // We can move N cells in either of 4 directions
                int x = curr.Item1 + row[i] * n;
                int y = curr.Item2 + col[i] * n;
                var next = (x, y);
                // if valid pair
                if (IsValid(visited, next))
                {
                    // mark cell as visited
                    visited.Add(next);
                    // add cell to current path
                    path.Add(next);
                    // recurse for next cell
                    FindPathInMazeUtil(maze, path, visited, next);
                    // backtrack
                    // remove cell from current path
                    path.RemoveAt(path.Count - 1);
                    visited.Remove(next);
                }
            }
        }
 
        // Function to find a path from corner cell to
        // middle cell in maze containing positive numbers
        static void FindPathInMaze(int[][] maze)
        {
            // list to store complete path
            // from source to destination
            var path = new List<(int, int)>();
            // to store cells already visited in current path
            var visited = new List<(int, int)>();
 
            // Consider each corners as the starting
            // point and search in maze
            for (int i = 0; i < 4; i++)
            {
                int x = _row[i];
                int y = _col[i];
                var pt = (x, y);
                
            // mark cell as visited
            visited.Add(pt);
            // add cell to current path
            path.Add(pt);
            FindPathInMazeUtil(maze, path, visited, pt);
            // backtrack
            // remove cell from current path
            path.RemoveAt(path.Count - 1);
            visited.Remove(pt);
        }
    }
 
    static void Main(string[] args)
    {
        int[][] maze = new int[][] {
            new int[] {3, 5, 4, 4, 7, 3, 4, 6, 3},
            new int[] {6, 7, 5, 6, 6, 2, 6, 6, 2},
            new int[] {3, 3, 4, 3, 2, 5, 4, 7, 2},
            new int[] {6, 5, 5, 1, 2, 3, 6, 5, 6},
            new int[] {3, 3, 4, 3, 0, 1, 4, 3, 4},
            new int[] {3, 5, 4, 3, 2, 2, 3, 3, 5},
            new int[] {3, 5, 4, 3, 2, 6, 4, 4, 3},
            new int[] {3, 5, 1, 3, 7, 5, 3, 6, 4},
            new int[] {6, 2, 4, 3, 4, 5, 4, 5, 1}
        };
 
        FindPathInMaze(maze);
    }
  }
}


Javascript




// JavaScript program to find a path from corner cell to
// middle cell in maze containing positive numbers
 
// Rows and columns in given maze
let N = 9;
 
// check whether given cell is a valid cell or not.
function isValid(visited, pt) {
     
    // check if cell is not visited yet to
    // avoid cycles (infinite loop) and its
    // row and column number is in range
    return (pt[0] >= 0) && (pt[0] < N) && (pt[1] >= 0) && (pt[1] < N) &&
    (!visited.some(item => item[0] === pt[0] && item[1] === pt[1]));
}
 
// Function to print path from source to middle coordinate
function printPath(path) {
    let pathStr = "";
    for (let i of path) {
        pathStr += "(" + i[0] + ", " + i[1] + ") -> ";
    }
    pathStr += "MID";
    console.log(pathStr);
    console.log();
}
 
// For searching in all 4 direction
const row = [-1, 1, 0, 0];
const col = [0, 0, -1, 1];
 
// Coordinates of 4 corners of matrix
const _row = [0, 0, N-1, N-1];
const _col = [0, N-1, 0, N-1];
 
function findPathInMazeUtil(maze, path, visited, curr) {
     
    // If we have reached the destination cell.
    // print the complete path
    if (curr[0] === Math.floor(N / 2) && curr[1] === Math.floor(N / 2)) {
        printPath(path);
        return;
    }
     
    // consider each direction
    for (let i = 0; i < 4; i++) {
         
        // get value of current cell
        let n = maze[curr[0]][curr[1]];
         
        // We can move N cells in either of 4 directions
        let x = curr[0] + row[i]*n;
        let y = curr[1] + col[i]*n;
         
        // Constructs a pair object with its first element
        // set to x and its second element set to y
        let next = [x, y];
         
        // if valid pair
        if (isValid(visited, next)) {
             
            // mark cell as visited
            visited.push(next);
             
            // add cell to current path
            path.push(next);
             
            // recurse for next cell
            findPathInMazeUtil(maze, path, visited, next);
             
            // backtrack
            path.pop();
             
            // remove cell from current path
            visited = visited.filter(item => item[0] !== next[0] || item[1] !== next[1]);
        }
    }
}
 
// Function to find a path from corner cell to
// middle cell in maze containing positive numbers
function findPathInMaze(maze) {
     
    // list to store complete path
    // from source to destination
    let path = [];
     
    // to store cells already visited in current path
    let visited = [];
     
    // Consider each corners as the starting
    // point and search in maze
    for (let i = 0; i < 4; i++) {
        let x = _row[i];
        let y = _col[i];
         
        // Constructs a pair object
        let pt = [x, y];
         
        // mark cell as visited
        visited.push(pt);
         
        // add cell to current path
        path.push(pt);
         
        findPathInMazeUtil(maze, path, visited, pt);
         
        // backtrack
        path.pop();
         
        // remove cell from current path
        visited = visited.filter(item => item[0] !== pt[0] || item[1] !== pt[1]);
    }
}
 
let maze = [
        [3, 5, 4, 4, 7, 3, 4, 6, 3],
        [6, 7, 5, 6, 6, 2, 6, 6, 2],
        [3, 3, 4, 3, 2, 5, 4, 7, 2],
        [6, 5, 5, 1, 2, 3, 6, 5, 6],
        [3, 3, 4, 3, 0, 1, 4, 3, 4],
        [3, 5, 4, 3, 2, 2, 3, 3, 5],
        [3, 5, 4, 3, 2, 6, 4, 4, 3],
        [3, 5, 1, 3, 7, 5, 3, 6, 4],
        [6, 2, 4, 3, 4, 5, 4, 5, 1]
    ]
findPathInMaze(maze)
// This code is contributed by prasad264


Java




import java.util.*;
 
public class MazePathFinder {
 
    // Rows and columns in given maze
    private static int N = 9;
    // For searching in all 4 direction
    private static int[] row = { -1, 1, 0, 0 };
    private static int[] col = { 0, 0, -1, 1 };
    // Coordinates of 4 corners of matrix
    private static int[] _row = { 0, 0, N - 1, N - 1 };
    private static int[] _col = { 0, N - 1, 0, N - 1 };
 
    // check whether given cell is a valid cell or not.
    private static boolean isValid(ArrayList<int[]> visited,
                                   int[] pt)
    {
        // check if cell is not visited yet to
        // avoid cycles (infinite loop) and its
        // row and column number is in range
        return (pt[0] >= 0) && (pt[0] < N) && (pt[1] >= 0)
            && (pt[1] < N)
            && (!visited.stream().anyMatch(
                item
                -> item[0] == pt[0] && item[1] == pt[1]));
    }
    // Function to print path from source to middle
    // coordinate
    private static void printPath(ArrayList<int[]> path)
    {
        String pathStr = "";
        for (int[] i : path) {
            pathStr += "(" + i[0] + ", " + i[1] + ") -> ";
        }
        pathStr += "MID";
        System.out.println(pathStr);
        System.out.println();
    }
 
    private static void
    findPathInMazeUtil(int[][] maze, ArrayList<int[]> path,
                       ArrayList<int[]> visited, int[] curr)
    {
        // If we have reached the destination cell.
        // print the complete path
        if (curr[0] == (N / 2) && curr[1] == (N / 2)) {
            printPath(path);
            return;
        }
        // consider each direction
        for (int i = 0; i < 4; i++) {
            // get value of current cell
            int n = maze[curr[0]][curr[1]];
            // We can move N cells in either of 4 directions
            int x = curr[0] + row[i] * n;
            int y = curr[1] + col[i] * n;
            int[] next = { x, y };
            // if valid pair
            if (isValid(visited, next)) {
                // mark cell as visited
                visited.add(next);
                // add cell to current path
                path.add(next);
                // recurse for next cell
                findPathInMazeUtil(maze, path, visited,
                                   next);
                // backtrack
                // remove cell from current path
                path.remove(path.size() - 1);
                visited.removeIf(item
                                 -> item[0] == next[0]
                                        && item[1]
                                               == next[1]);
            }
        }
    }
    // Function to find a path from corner cell to
    // middle cell in maze containing positive numbers
    public static void findPathInMaze(int[][] maze)
    {
        // list to store complete path
        // from source to destination
        ArrayList<int[]> path = new ArrayList<>();
        // to store cells already visited in current path
        ArrayList<int[]> visited = new ArrayList<>();
        // Consider each corners as the starting
        // point and search in maze
        for (int i = 0; i < 4; i++) {
            int x = _row[i];
            int y = _col[i];
            int[] pt = { x, y };
            // mark cell as visited
            visited.add(pt);
            // add cell to current path
            path.add(pt);
            findPathInMazeUtil(maze, path, visited, pt);
            // backtrack
            // remove cell from current path
            path.remove(path.size() - 1);
            visited.removeIf(item
                             -> item[0] == pt[0]
                                    && item[1] == pt[1]);
        }
    }
    public static void main(String[] args)
    {
        // input maze
        int[][] maze = { { 3, 5, 4, 4, 7, 3, 4, 6, 3 },
                         { 6, 7, 5, 6, 6, 2, 6, 6, 2 },
                         { 3, 3, 4, 3, 2, 5, 4, 7, 2 },
                         { 6, 5, 5, 1, 2, 3, 6, 5, 6 },
                         { 3, 3, 4, 3, 0, 1, 4, 3, 4 },
                         { 3, 5, 4, 3, 2, 2, 3, 3, 5 },
                         { 3, 5, 4, 3, 2, 6, 4, 4, 3 },
                         { 3, 5, 1, 3, 7, 5, 3, 6, 4 },
                         { 6, 2, 4, 3, 4, 5, 4, 5, 1 } };
 
        // find path from corner cell to middle cell in the
        // maze
        findPathInMaze(maze);
    }
}


Output

(0, 0) -> (0, 3) -> (0, 7) -> (6, 7) -> (6, 3) -> (3, 3) -> (3, 4) -> (5, 4) -> (5, 2) -> (1, 2) -> (1, 7) -> (7, 7) -> (7, 1) -> (2, 1) -> (2, 4) -> (4, 4) -> MID

Output : 

(0, 0) -> (0, 3) -> (0, 7) -> 
(6, 7) -> (6, 3) -> (3, 3) -> 
(3, 4) -> (5, 4) -> (5, 2) -> 
(1, 2) -> (1, 7) -> (7, 7) ->
(7, 1) -> (2, 1) -> (2, 4) -> 
(4, 4) -> MID

Time Complexity: O(4^N2), where N is the size of the maze and the program may need to explore all possible paths in the maze before finding the path from the corner to the middle cell.

Space Complexity: O(N2), where N*N is the size of the maze.

A better approach:  

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
void printPath(vector<vector<int>>&maze, int i, int j, string ans){
 
  
    // If we reach the center cell
    if (i == maze.size()/2 && j==maze.size()/2){
  
        // Make the final answer, Print the
        // final answer and Return
        ans += "(";
        ans += to_string(i);
        ans += ", ";
        ans += to_string(j);
        ans += ") -> MID";
        cout<<ans<<endl;
        return;
    }
          
    // If the element at the current position
    // in maze is 0, simply Return as it has
    // been visited before.
    if (maze[i][j]==0){
        return;
    }
      
    // If element is non-zero, then note
    // the element in variable 'k'
    int k = maze[i][j];
      
    // Mark the cell visited by making the
    // element 0. Don't worry, the element
    // is safe in 'k'
    maze[i][j]=0;
      
    // Make recursive calls in all 4
    // directions pro-actively i.e. if the next
    // cell lies in maze or not. Right call
    ans += "(";
    ans += to_string(i);
    ans += ", ";
    ans += to_string(j);
    ans += ") -> ";
 
    if (j+k<maze.size()){
        printPath(maze, i, j+k, ans);
    }
  
    // down call
    if (i+k<maze.size()){
        printPath(maze, i+k, j,ans);
    }
  
    // left call
    if (j-k>0){
        printPath(maze, i, j-k, ans);
    }
  
    // up call
    if (i-k>0){
        printPath(maze, i-k, j, ans);
    }
      
    // Unmark the visited cell by substituting
    // its original value from 'k'
    maze[i][j] = k;
 
}
 
int main () {
  
    // Creating the maze
    vector<vector<int>>maze = {
        { 3, 5, 4, 4, 7, 3, 4, 6, 3 },
        { 6, 7, 5, 6, 6, 2, 6, 6, 2 },
        { 3, 3, 4, 3, 2, 5, 4, 7, 2 },
        { 6, 5, 5, 1, 2, 3, 6, 5, 6 },
        { 3, 3, 4, 3, 0, 1, 4, 3, 4 },
        { 3, 5, 4, 3, 2, 2, 3, 3, 5 },
        { 3, 5, 4, 3, 2, 6, 4, 4, 3 },
        { 3, 5, 1, 3, 7, 5, 3, 6, 4 },
        { 6, 2, 4, 3, 4, 5, 4, 5, 1 }
    };
      
    // Calling the printPath function
    printPath(maze,0,0,"");
}
 
// This code is contributed by shinjanpatra


Java




// Java program to find a path from corner cell to
// middle cell in maze containing positive numbers
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
 
        // Creating the maze
        int[][] maze = {
            { 3, 5, 4, 4, 7, 3, 4, 6, 3 },
            { 6, 7, 5, 6, 6, 2, 6, 6, 2 },
            { 3, 3, 4, 3, 2, 5, 4, 7, 2 },
            { 6, 5, 5, 1, 2, 3, 6, 5, 6 },
            { 3, 3, 4, 3, 0, 1, 4, 3, 4 },
            { 3, 5, 4, 3, 2, 2, 3, 3, 5 },
            { 3, 5, 4, 3, 2, 6, 4, 4, 3 },
            { 3, 5, 1, 3, 7, 5, 3, 6, 4 },
            { 6, 2, 4, 3, 4, 5, 4, 5, 1 }
        };
         
        // Calling the printPath function
        printPath(maze,0,0,"");
    }
     
    public static void printPath(int[][] maze, int i, int j, String ans){
 
        // If we reach the center cell
        if (i == maze.length/2 && j==maze.length/2){
 
            // Make the final answer, Print the
                // final answer and Return
            ans += "("+i+", "+j+") -> MID";
            System.out.println(ans);
            return;
        }
         
        // If the element at the current position
            // in maze is 0, simply Return as it has
            // been visited before.
        if (maze[i][j]==0){
            return;
        }
         
        // If element is non-zero, then note
            // the element in variable 'k'
        int k = maze[i][j];
         
        // Mark the cell visited by making the
            // element 0. Don't worry, the element
            // is safe in 'k'
        maze[i][j]=0;
         
        // Make recursive calls in all 4
            // directions pro-actively i.e. if the next
            // cell lies in maze or not. Right call
        if (j+k<maze.length){
            printPath(maze, i, j+k, ans+"("+i+", "+j+") -> ");
        }
 
        // down call
        if (i+k<maze.length){
            printPath(maze, i+k, j, ans+"("+i+", "+j+") -> ");
        }
 
        // left call
        if (j-k>0){
            printPath(maze, i, j-k, ans+"("+i+", "+j+") -> ");
        }
 
        // up call
        if (i-k>0){
            printPath(maze, i-k, j, ans+"("+i+", "+j+") -> ");
        }
         
        // Unmark the visited cell by substituting
            // its original value from 'k'
        maze[i][j] = k;
    }
                         
}


Python3




# Python program to find a path from corner cell to
# middle cell in maze containing positive numbers
def printPath(maze, i, j, ans):
 
    # If we reach the center cell
    if (i == len(maze) // 2 and j == len(maze) // 2):
 
        # Make the final answer, Print
        # final answer and Return
        ans += "(" + str(i) + ", " + str(j) + ") -> MID";
        print(ans);
        return;
     
    # If the element at the current position
    # in maze is 0, simply Return as it has
    # been visited before.
    if (maze[i][j] == 0):
        return;
     
    # If element is non-zero, then note
    # the element in variable 'k'
    k = maze[i][j];
 
    # Mark the cell visited by making the
    # element 0. Don't worry, the element
    # is safe in 'k'
    maze[i][j] = 0;
 
    # Make recursive calls in all 4
    # directions pro-actively i.e. if the next
    # cell lies in maze or not. Right call
    if (j + k < len(maze)):
        printPath(maze, i, j + k, ans + "(" + str(i) + ", " + str(j) + ") -> ");
     
    # down call
    if (i + k < len(maze)):
        printPath(maze, i + k, j, ans + "(" + str(i) + ", " + str(j) + ") -> ");
     
    # left call
    if (j - k > 0):
        printPath(maze, i, j - k, ans + "(" + str(i) + ", " + str(j) + ") -> ");
     
    # up call
    if (i - k > 0):
        printPath(maze, i - k, j, ans + "(" + str(i) + ", " + str(j) + ") -> ");
     
    # Unmark the visited cell by substituting
    # its original value from 'k'
    maze[i][j] = k;
 
    # Driver code
if __name__ == '__main__':
 
    # Creating the maze
    maze = [[ 3, 5, 4, 4, 7, 3, 4, 6, 3 ],[ 6, 7, 5, 6, 6, 2, 6, 6, 2 ],[ 3, 3, 4, 3, 2, 5, 4, 7, 2 ],
            [ 6, 5, 5, 1, 2, 3, 6, 5, 6 ],[ 3, 3, 4, 3, 0, 1, 4, 3, 4 ],[ 3, 5, 4, 3, 2, 2, 3, 3, 5 ],
            [ 3, 5, 4, 3, 2, 6, 4, 4, 3 ],[ 3, 5, 1, 3, 7, 5, 3, 6, 4 ],[ 6, 2, 4, 3, 4, 5, 4, 5, 1 ]] ;
 
    # Calling the printPath function
    printPath(maze, 0, 0, "");
 
# This code contributed by gauravrajput1


C#




// C# program to find a path from corner
// cell to middle cell in maze containing
// positive numbers
using System;
 
class GFG{
 
// Driver Code   
public static void Main(String[] args)
{
     
    // Creating the maze
    int[,] maze = {
        { 3, 5, 4, 4, 7, 3, 4, 6, 3 },
        { 6, 7, 5, 6, 6, 2, 6, 6, 2 },
        { 3, 3, 4, 3, 2, 5, 4, 7, 2 },
        { 6, 5, 5, 1, 2, 3, 6, 5, 6 },
        { 3, 3, 4, 3, 0, 1, 4, 3, 4 },
        { 3, 5, 4, 3, 2, 2, 3, 3, 5 },
        { 3, 5, 4, 3, 2, 6, 4, 4, 3 },
        { 3, 5, 1, 3, 7, 5, 3, 6, 4 },
        { 6, 2, 4, 3, 4, 5, 4, 5, 1 }
    };
     
    // Calling the printPath function
    printPath(maze, 0, 0, "");
}
 
public static void printPath(int[,] maze, int i,
                             int j, String ans)
{
     
    // If we reach the center cell
    if (i == maze.GetLength(0) / 2 &&
        j == maze.GetLength(1) / 2)
    {
         
        // Make the readonly answer, Print the
        // readonly answer and Return
        ans += "(" + i + ", " + j + ") -> MID";
        Console.WriteLine(ans);
        return;
    }
     
    // If the element at the current position
    // in maze is 0, simply Return as it has
    // been visited before.
    if (maze[i, j] == 0)
    {
        return;
    }
     
    // If element is non-zero, then note
    // the element in variable 'k'
    int k = maze[i, j];
     
    // Mark the cell visited by making the
    // element 0. Don't worry, the element
    // is safe in 'k'
    maze[i, j] = 0;
     
    // Make recursive calls in all 4
    // directions pro-actively i.e. if the next
    // cell lies in maze or not. Right call
    if (j + k < maze.GetLength(1))
    {
        printPath(maze, i, j + k,
                  ans + "(" + i +
                  ", " + j + ") -> ");
    }
 
    // Down call
    if (i + k < maze.GetLength(0))
    {
        printPath(maze, i + k, j,
                  ans + "(" + i +
                  ", " + j + ") -> ");
    }
 
    // Left call
    if (j - k > 0)
    {
        printPath(maze, i, j - k,
                  ans + "(" + i +
                  ", " + j + ") -> ");
    }
 
    // Up call
    if (i - k > 0)
    {
        printPath(maze, i - k, j,
                  ans + "(" + i +
                  ", " + j + ") -> ");
    }
     
    // Unmark the visited cell by substituting
    // its original value from 'k'
    maze[i, j] = k;
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
// Javascript program to find a path from corner cell to
// middle cell in maze containing positive numbers
 
function printPath( maze,i,j,ans)
{
    // If we reach the center cell
        if (i == Math.floor(maze.length/2) && j == Math.floor(maze.length/2))
        {
  
            // Make the final answer, Print the
                // final answer and Return
            ans += "("+i+", "+j+") -> MID";
            document.write(ans+"<br>");
            return;
        }
          
        // If the element at the current position
            // in maze is 0, simply Return as it has
            // been visited before.
        if (maze[i][j] == 0){
            return;
        }
          
        // If element is non-zero, then note
            // the element in variable 'k'
        let k = maze[i][j];
          
        // Mark the cell visited by making the
            // element 0. Don't worry, the element
            // is safe in 'k'
        maze[i][j] = 0;
          
        // Make recursive calls in all 4
            // directions pro-actively i.e. if the next
            // cell lies in maze or not. Right call
        if (j + k < maze.length){
            printPath(maze, i, j+k, ans+"("+i+", "+j+") -> ");
        }
  
        // down call
        if (i + k < maze.length){
            printPath(maze, i+k, j, ans+"("+i+", "+j+") -> ");
        }
  
        // left call
        if (j-k>0){
            printPath(maze, i, j-k, ans+"("+i+", "+j+") -> ");
        }
  
        // up call
        if (i-k>0){
            printPath(maze, i-k, j, ans+"("+i+", "+j+") -> ");
        }
          
        // Unmark the visited cell by substituting
            // its original value from 'k'
        maze[i][j] = k;
}
 
let maze = [[ 3, 5, 4, 4, 7, 3, 4, 6, 3 ],[ 6, 7, 5, 6, 6, 2, 6, 6, 2 ],[ 3, 3, 4, 3, 2, 5, 4, 7, 2 ],
            [ 6, 5, 5, 1, 2, 3, 6, 5, 6 ],[ 3, 3, 4, 3, 0, 1, 4, 3, 4 ],[ 3, 5, 4, 3, 2, 2, 3, 3, 5 ],
            [ 3, 5, 4, 3, 2, 6, 4, 4, 3 ],[ 3, 5, 1, 3, 7, 5, 3, 6, 4 ],[ 6, 2, 4, 3, 4, 5, 4, 5, 1 ]] ;
printPath(maze, 0, 0, "");
 
// This code is contributed by unknown2108
</script>


Output

(0, 0) -> (0, 3) -> (0, 7) -> 
(6, 7) -> (6, 3) -> (3, 3) ->
(3, 4) -> (5, 4) -> (5, 2) ->
(1, 2) -> (1, 7) -> (7, 7) -> 
(7, 1) -> (2, 1) -> (2, 4) -> 
(4, 4) -> MID

Time Complexity: O(4^N2), where N is the size of the maze and the function makes recursive calls in all four directions, resulting in a branching factor of 4.

Space Complexity: O(N2), where N is the size of the maze. This is because the function uses a 2D vector to represent the maze, which has N^2 elements.

 



Previous Article
Next Article

Similar Reads

Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
Given a matrix arr[][] of dimensions N * M, having elements 0, 1, and 2. There is only one cell with value 1 present in the matrix. The task is to check if it is possible for 1 to reach the bottom right corner before any cell valued 2 or not using the following operations: 2 can replicate itself 1 unit in all four directions in 1 unit of time.1 can
11 min read
Find the maximum cost path from the bottom-left corner to the top-right corner
Given a two dimensional grid, each cell of which contains integer cost which represents a cost to traverse through that cell. The task is to find the maximum cost path from the bottom-left corner to the top-right corner.Note: Use up and right moves only Examples: Input : mat[][] = {{20, -10, 0}, {1, 5, 10}, {1, 2, 3}} Output : 18 (2, 0) ==&gt; (2,
9 min read
Number of shortest paths to reach every cell from bottom-left cell in the grid
Given two number N and M. The task is to find the number of shortest paths to reach the cell(i, j) in the grid of size N × M when the moves started from the bottom-left cornerNote: cell(i, j) represents the ith row and jth column in the gridBelow image shows some of the shortest paths to reach cell(1, 4) in 4 × 4 grid Examples : Input : N = 3, M =
6 min read
Minimum cells traversed to reach corner where every cell represents jumps
Suppose A is at position (0, 0) of a 2-D grid containing 'm' rows and 'n' columns. His aim is to reach the bottom right point of this grid traveling through as minimum number of cells as possible.Each cell of the grid contains a positive integer that defines the number of cells A can jump either in the right or the downward direction when he reache
9 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.Examples: Input: mat[][] = {{1, 2}, {3, 1}} Output: 0 Explanation: Ev
18 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell. Examples: Input: M = 2, N = 2, mat[M][N] = {{0, 0}, {0, 1}} Output:
12 min read
Find the largest sum of a cycle in the maze
Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn't have an exit. The task is
9 min read
Sum of cost of all paths to reach a given cell in a Matrix
Given a matrix grid[][] and two integers M and N, the task is to find the sum of cost of all possible paths from the (0, 0) to (M, N) by moving a cell down or right. Cost of each path is defined as the sum of values of the cells visited in the path.Examples: Input: M = 1, N = 1, grid[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output: 18 Explanation: T
8 min read
Rat in a Maze | Backtracking using Stack
Prerequisites - Recursion, Backtracking and Stack Data Structure. A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used
16 min read
A variation of Rat in a Maze : multiple steps or jumps allowed
A variation of rat in a maze. You are given an N * N 2-D matrix shaped maze (let's call it M), there is a rat in the top-left cell i.e. M[0][0] and there is an escape door in the bottom-right cell i.e. M[N-1][N-1]. From each cell M[i][j] (0 ? i ? N-1, 0 ? j ? N-1) the rat can go a number of steps towards its right ( for eg: to M[i][j+ s]), or a num
15 min read
Article Tags :
Practice Tags :