Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
Find shortest safe route in a path with landmines
Next article icon

Longest Possible Route in a Matrix with Hurdles

Last Updated : 04 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location once visited in a particular path cannot be visited again.

For example, the longest path with no hurdles from source to destination is highlighted below. The length of the path is 24.

The idea is to use Backtracking. We start from the source cell of the matrix, move forward in all four allowed directions, and recursively checks if they lead to the solution or not. If the destination is found, we update the value of the longest path else if none of the above solutions work we return false from our function.

Below is the implementation of the above idea 

CPP
// C++ program to find Longest Possible Route in a // matrix with hurdles #include <bits/stdc++.h> using namespace std; #define R 3 #define C 10  // A Pair to store status of a cell. found is set to // true of destination is reachable and value stores // distance of longest path struct Pair {     // true if destination is found     bool found;      // stores cost of longest path from current cell to     // destination cell     int value; };  // Function to find Longest Possible Route in the // matrix with hurdles. If the destination is not reachable // the function returns false with cost INT_MAX. // (i, j) is source cell and (x, y) is destination cell. Pair findLongestPathUtil(int mat[R][C], int i, int j, int x,                          int y, bool visited[R][C]) {      // if (i, j) itself is destination, return true     if (i == x && j == y) {         Pair p = { true, 0 };         return p;     }      // if not a valid cell, return false     if (i < 0 || i >= R || j < 0 || j >= C || mat[i][j] == 0         || visited[i][j]) {         Pair p = { false, INT_MAX };         return p;     }      // include (i, j) in current path i.e.     // set visited(i, j) to true     visited[i][j] = true;      // res stores longest path from current cell (i, j) to     // destination cell (x, y)     int res = INT_MIN;      // go left from current cell     Pair sol         = findLongestPathUtil(mat, i, j - 1, x, y, visited);      // if destination can be reached on going left from     // current cell, update res     if (sol.found)         res = max(res, sol.value);      // go right from current cell     sol = findLongestPathUtil(mat, i, j + 1, x, y, visited);      // if destination can be reached on going right from     // current cell, update res     if (sol.found)         res = max(res, sol.value);      // go up from current cell     sol = findLongestPathUtil(mat, i - 1, j, x, y, visited);      // if destination can be reached on going up from     // current cell, update res     if (sol.found)         res = max(res, sol.value);      // go down from current cell     sol = findLongestPathUtil(mat, i + 1, j, x, y, visited);      // if destination can be reached on going down from     // current cell, update res     if (sol.found)         res = max(res, sol.value);      // Backtrack     visited[i][j] = false;      // if destination can be reached from current cell,     // return true     if (res != INT_MIN) {         Pair p = { true, 1 + res };         return p;     }      // if destination can't be reached from current cell,     // return false     else {         Pair p = { false, INT_MAX };         return p;     } }  // A wrapper function over findLongestPathUtil() void findLongestPath(int mat[R][C], int i, int j, int x,                      int y) {     // create a boolean matrix to store info about     // cells already visited in current route     bool visited[R][C];      // initialize visited to false     memset(visited, false, sizeof visited);      // find longest route from (i, j) to (x, y) and     // print its maximum cost     Pair p = findLongestPathUtil(mat, i, j, x, y, visited);     if (p.found)         cout << "Length of longest possible route is "              << p.value;      // If the destination is not reachable     else         cout << "Destination not reachable from given "                 "source"; }  // Driver code int main() {     // input matrix with hurdles shown with number 0     int mat[R][C] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                       { 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 },                       { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };      // find longest path with source (0, 0) and     // destination (1, 7)     findLongestPath(mat, 0, 0, 1, 7);      return 0; } 
Java
// Java program to find Longest Possible Route in a // matrix with hurdles import java.io.*;  class GFG {   static int R = 3;   static int C = 10;    // A Pair to store status of a cell. found is set to   // true of destination is reachable and value stores   // distance of longest path   static class Pair {      // true if destination is found     boolean found;      // stores cost of longest path from current cell to     // destination cell     int val;      Pair (boolean x, int y){       found = x;       val = y;     }   }    // Function to find Longest Possible Route in the   // matrix with hurdles. If the destination is not reachable   // the function returns false with cost Integer.MAX_VALUE.   // (i, j) is source cell and (x, y) is destination cell.    static Pair findLongestPathUtil (int mat[][], int i, int j, int x, int y, boolean visited[][]) {      // if (i, j) itself is destination, return true     if(i == x && j == y)       return new Pair(true, 0);       // if not a valid cell, return false       if(i < 0 || i >= R || j < 0 || j >= C || mat[i][j] == 0 || visited[i][j] )       return new Pair(false, Integer.MAX_VALUE);      // include (i, j) in current path i.e.     // set visited(i, j) to true     visited[i][j] = true;      // res stores longest path from current cell (i, j) to     // destination cell (x, y)     int res = Integer.MIN_VALUE;      // go left from current cell     Pair sol = findLongestPathUtil(mat, i, j-1, x, y, visited);      // if destination can be reached on going left from current     // cell, update res     if(sol.found)       res = Math.max(sol.val, res);      // go right from current cell     sol = findLongestPathUtil(mat, i, j+1, x, y, visited);      // if destination can be reached on going right from current     // cell, update res     if(sol.found)       res = Math.max(sol.val, res);      // go up from current cell     sol = findLongestPathUtil(mat, i-1, j, x, y, visited);      // if destination can be reached on going up from current     // cell, update res     if(sol.found)       res = Math.max(sol.val, res);      // go down from current cell     sol = findLongestPathUtil(mat, i+1, j, x, y, visited);      // if destination can be reached on going down from current     // cell, update res     if(sol.found)       res = Math.max(sol.val, res);      // Backtrack     visited[i][j] = false;      // if destination can be reached from current cell,     // return true     if(res != Integer.MIN_VALUE)       return new Pair(true, res+1);      // if destination can't be reached from current cell,     // return false     else       return new Pair(false, Integer.MAX_VALUE);    }      // A wrapper function over findLongestPathUtil()   static void findLongestPath (int mat[][], int i, int j, int x, int y) {      // create a boolean matrix to store info about     // cells already visited in current route     boolean visited[][] = new boolean[R][C];       // find longest route from (i, j) to (x, y) and     // print its maximum cost     Pair p = findLongestPathUtil(mat, i, j, x, y, visited);      if(p.found)       System.out.println("Length of longest possible route is " + p.val);      // If the destination is not reachable     else       System.out.println("Destination not reachable from given source");    }     // Driver Code   public static void main (String[] args) {      // input matrix with hurdles shown with number 0     int mat[][] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                    { 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 },                    { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };      // find longest path with source (0, 0) and     // destination (1, 7)     findLongestPath(mat, 0, 0, 1, 7);    } }  // This code is contributed by th_aditi. 
Python3
# Python program to find Longest Possible Route in a # matrix with hurdles import sys R,C = 3,10  # A Pair to store status of a cell. found is set to # True of destination is reachable and value stores # distance of longest path class Pair:          def __init__(self, found, value):         self.found = found          self.value = value  # Function to find Longest Possible Route in the # matrix with hurdles. If the destination is not reachable # the function returns false with cost sys.maxsize. # (i, j) is source cell and (x, y) is destination cell. def findLongestPathUtil(mat, i, j, x, y, visited):      # if (i, j) itself is destination, return True     if (i == x and j == y):         p = Pair( True, 0 )         return p          # if not a valid cell, return false     if (i < 0 or i >= R or j < 0 or j >= C or mat[i][j] == 0 or visited[i][j]) :         p = Pair( False, sys.maxsize )         return p      # include (i, j) in current path i.e.     # set visited(i, j) to True     visited[i][j] = True      # res stores longest path from current cell (i, j) to     # destination cell (x, y)     res = -sys.maxsize -1      # go left from current cell     sol = findLongestPathUtil(mat, i, j - 1, x, y, visited)      # if destination can be reached on going left from     # current cell, update res     if (sol.found):         res = max(res, sol.value)      # go right from current cell     sol = findLongestPathUtil(mat, i, j + 1, x, y, visited)      # if destination can be reached on going right from     # current cell, update res     if (sol.found):         res = max(res, sol.value)      # go up from current cell     sol = findLongestPathUtil(mat, i - 1, j, x, y, visited)      # if destination can be reached on going up from     # current cell, update res     if (sol.found):         res = max(res, sol.value)      # go down from current cell     sol = findLongestPathUtil(mat, i + 1, j, x, y, visited)      # if destination can be reached on going down from     # current cell, update res     if (sol.found):         res = max(res, sol.value)      # Backtrack     visited[i][j] = False      # if destination can be reached from current cell,     # return True     if (res != -sys.maxsize -1):         p = Pair( True, 1 + res )         return p          # if destination can't be reached from current cell,     # return false     else:         p = Pair( False, sys.maxsize )         return p  # A wrapper function over findLongestPathUtil() def findLongestPath(mat, i, j, x,y):      # create a boolean matrix to store info about     # cells already visited in current route     # initialize visited to false     visited = [[False for i in range(C)]for j in range(R)]      # find longest route from (i, j) to (x, y) and     # print its maximum cost     p = findLongestPathUtil(mat, i, j, x, y, visited)     if (p.found):         print("Length of longest possible route is ",str(p.value))      # If the destination is not reachable     else:         print("Destination not reachable from given source")  # Driver code  # input matrix with hurdles shown with number 0 mat = [ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ]  # find longest path with source (0, 0) and # destination (1, 7) findLongestPath(mat, 0, 0, 1, 7)  # This code is contributed by shinjanpatra 
C#
// Java program to find Longest Possible Route in a // matrix with hurdles using System;  class GFG {   static int R = 3;   static int C = 10;    // Function to find Longest Possible Route in the   // matrix with hurdles. If the destination is not reachable   // the function returns false with cost Integer.MAX_VALUE.   // (i, j) is source cell and (x, y) is destination cell.    static Tuple<bool,int> findLongestPathUtil (int[, ] mat, int i, int j, int x, int y, bool[, ] visited) {      // if (i, j) itself is destination, return true     if(i == x && j == y)       return new Tuple<bool,int>(true, 0);       // if not a valid cell, return false       if(i < 0 || i >= R || j < 0 || j >= C || mat[i,j] == 0 || visited[i,j])       return new Tuple<bool,int>(false, Int32.MaxValue);      // include (i, j) in current path i.e.     // set visited(i, j) to true     visited[i,j] = true;      // res stores longest path from current cell (i, j) to     // destination cell (x, y)     int res = Int32.MinValue;      // go left from current cell     Tuple<bool,int> sol = findLongestPathUtil(mat, i, j-1, x, y, visited);      // if destination can be reached on going left from current     // cell, update res     if(sol.Item1)       res = Math.Max(sol.Item2, res);      // go right from current cell     sol = findLongestPathUtil(mat, i, j+1, x, y, visited);      // if destination can be reached on going right from current     // cell, update res     if(sol.Item1)       res = Math.Max(sol.Item2, res);      // go up from current cell     sol = findLongestPathUtil(mat, i-1, j, x, y, visited);      // if destination can be reached on going up from current     // cell, update res     if(sol.Item1)       res = Math.Max(sol.Item2, res);      // go down from current cell     sol = findLongestPathUtil(mat, i+1, j, x, y, visited);      // if destination can be reached on going down from current     // cell, update res     if(sol.Item1)       res = Math.Max(sol.Item2, res);      // Backtrack     visited[i,j] = false;      // if destination can be reached from current cell,     // return true     if(res != Int32.MinValue)       return new Tuple<bool,int>(true, res+1);      // if destination can't be reached from current cell,     // return false     else       return new Tuple<bool,int>(false, Int32.MaxValue);    }      // A wrapper function over findLongestPathUtil()   static void findLongestPath (int [, ]mat, int i, int j, int x, int y) {      // create a boolean matrix to store info about     // cells already visited in current route     bool[,] visited = new bool[R,C];       // find longest route from (i, j) to (x, y) and     // print its maximum cost     Tuple<bool,int> p = findLongestPathUtil(mat, i, j, x, y, visited);      if(p.Item1)       Console.WriteLine("Length of longest possible route is : " + p.Item2);      // If the destination is not reachable     else       Console.WriteLine("Destination not reachable from given source");    }     // Driver Code   public static void Main() {      // input matrix with hurdles shown with number 0     int[,] mat = new int[,] { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                    { 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 },                    { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };      // find longest path with source (0, 0) and     // destination (1, 7)     findLongestPath(mat, 0, 0, 1, 7);    } }  // This code is contributed by Abhijeet Kumar(abhijeet19403) 
JavaScript
  // JavaScript program to find Longest Possible Route in a   // matrix with hurdles   var R = 3;   var C = 10;    // A Pair to store status of a cell. found is set to   // True of destination is reachable and value stores   // distance of longest path   class Pair {       constructor(found, value) {           this.found = found;           this.value = value;       }   }    // Function to find Longest Possible Route in the   // matrix with hurdles. If the destination is not reachable   // the function returns false with cost sys.maxsize.   // (i, j) is source cell and (x, y) is destination cell.   function findLongestPathUtil(mat, i, j, x, y, visited) {       // if (i, j) itself is destination, return True       if (i == x && j == y) {           var p = new Pair(true, 0);           return p;       }        // if not a valid cell, return false       if (i < 0 || i >= R || j < 0 || j >= C || mat[i][j] == 0 || visited[i][j]) {           var p = new Pair(false, Number.MAX_SAFE_INTEGER);           return p;       }        // include (i, j) in current path i.e.       // set visited(i, j) to True       visited[i][j] = true;        // res stores longest path from current cell (i, j) to       // destination cell (x, y)       var res = Number.MIN_SAFE_INTEGER ;        // go left from current cell       var sol = findLongestPathUtil(mat, i, j - 1, x, y, visited);        // if destination can be reached on going left from       // current cell, update res       if (sol.found) {           res = Math.max(res, sol.value);       }        // go right from current cell       sol = findLongestPathUtil(mat, i, j + 1, x, y, visited);        // if destination can be reached on going right from       // current cell, update res       if (sol.found) {           res = Math.max(res, sol.value);       }        // go up from current cell       sol = findLongestPathUtil(mat, i - 1, j, x, y, visited);        // if destination can be reached on going up from       // current cell, update res       if (sol.found) {           res = Math.max(res, sol.value);       }        // go down from current cell       sol = findLongestPathUtil(mat, i + 1, j, x, y, visited);        // if destination can be reached on going down from       // current cell, update res       if (sol.found) {           res = Math.max(res, sol.value);       }        // Backtrack       visited[i][j] = false;        // if destination can be reached from current cell,       // return True       if (res != Number.MIN_SAFE_INTEGER ) {           var p = new Pair(true, res+1);           return p;       }        // if destination can't be reached from current cell,       // return false       else {           var p = new Pair(false, Number.MAX_SAFE_INTEGER);           return p;       }   }    // A wrapper function over findLongestPathUtil()   function findLongestPath(mat, i, j, x, y) {       // create a boolean matrix to store info about       // cells already visited in current route       // initialize visited to false       var visited = new Array(R);       for (var k = 0; k < R; k++) {           visited[k] = new Array(C);       }        // find longest route from (i, j) to (x, y) and       // print its maximum cost       var p = findLongestPathUtil(mat, i, j, x, y, visited);       if (p.found) {           console.log("Length of longest possible route is " + p.value);       }       // If the destination is not reachable       else {           console.log("Destination not reachable from given source");       }   }    // Driver code    // input matrix with hurdles shown with number 0   var mat = [       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],       [1, 1, 0, 1, 1, 0, 1, 1, 0, 1],       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]   ];    // find longest path with source (0, 0) and   // destination (1, 7)   findLongestPath(mat, 0, 0, 1, 7);    // This code is contributed by Tapesh(tapeshdua420) 

Output
Length of longest possible route is 24

Time Complexity: 4^(R*C), Here R and C are the numbers of rows and columns respectively. For every index we have four options, so our overall time complexity will become 4^(R*C).
Auxiliary Space: O(R*C), The extra space is used in storing the elements of the visited matrix.

An approach without using any extra space:

Below is the step-by-step approach:

  1. Start from the source cell.
  2. Explore all possible directions (right, down, left, up) from the current cell.
  3. If a valid adjacent cell is found (within the boundaries of the matrix and has a value of 1), move to that cell and increment the current path length.
  4. Recursively repeat steps 2 and 3 for the new cell.
  5. If the destination cell is reached, compare the current path length with the longest path length found so far and update it if necessary.
  6. Backtrack by undoing the move (mark the current cell as visited) and continue exploring other directions.
  7. Repeat steps 2-6 until all possible paths are explored.
  8. Return the longest path length as the result.

Below is the implementation:

C++
#include <iostream> #include <vector> using namespace std;  // Function for finding the longest path // 'ans' is -1 if we can't reach // 'cur' is the number of steps we have traversed int findLongestPath(vector<vector<int> >& mat, int i, int j,                     int di, int dj, int n, int m,                     int cur = 0, int ans = -1) {     // If we reach the destination     if (i == di && j == dj) {         // If current path steps are more than previous path         // steps         if (cur > ans)             ans = cur;         return ans;     }          //if the source or destination is a hurdle itself       if(mat[i][j]==0 || mat[di][dj]==0) return;      // Mark as visited     mat[i][j] = 0;      // Checking if we can reach the destination going right     if (j != m - 1 && mat[i][j + 1] > 0)         ans = findLongestPath(mat, i, j + 1, di, dj, n, m,                               cur + 1, ans);      // Checking if we can reach the destination going down     if (i != n - 1 && mat[i + 1][j] > 0)         ans = findLongestPath(mat, i + 1, j, di, dj, n, m,                               cur + 1, ans);      // Checking if we can reach the destination going left     if (j != 0 && mat[i][j - 1] > 0)         ans = findLongestPath(mat, i, j - 1, di, dj, n, m,                               cur + 1, ans);      // Checking if we can reach the destination going up     if (i != 0 && mat[i - 1][j] > 0)         ans = findLongestPath(mat, i - 1, j, di, dj, n, m,                               cur + 1, ans);      // Marking visited to backtrack     mat[i][j] = 1;      // Returning the answer we got so far     return ans; }  int main() {     vector<vector<int> > mat = { { 1, 1, 1, 1 },                                  { 1, 1, 0, 1 },                                  { 1, 1, 1, 1 } };      // Find the longest path with source (0, 0) and     // destination (2, 3)     int result = findLongestPath(mat, 0, 0, 2, 3,                                  mat.size(), mat[0].size());     cout << result << endl;      return 0; } 
Java
public class Main {     // Function for finding the longest path     // 'ans' is -1 if we can't reach     // 'cur' is the number of steps we have traversed     public static int findLongestPath(int[][] mat, int i,                                       int j, int di, int dj,                                       int n, int m, int cur,                                       int ans)     {         // If we reach the destination         if (i == di && j == dj) {             // If current path steps are more than previous             // path steps             if (cur > ans)                 ans = cur;             return ans;         }            //if the source or destination is a hurdle itself           if(mat[i][j]==0 || mat[di][dj]==0) return ans;                // Mark as visited         mat[i][j] = 0;          // Checking if we can reach the destination going         // right         if (j != m - 1 && mat[i][j + 1] > 0)             ans = findLongestPath(mat, i, j + 1, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going         // down         if (i != n - 1 && mat[i + 1][j] > 0)             ans = findLongestPath(mat, i + 1, j, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going         // left         if (j != 0 && mat[i][j - 1] > 0)             ans = findLongestPath(mat, i, j - 1, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going up         if (i != 0 && mat[i - 1][j] > 0)             ans = findLongestPath(mat, i - 1, j, di, dj, n,                                   m, cur + 1, ans);          // Marking visited to backtrack         mat[i][j] = 1;          // Returning the answer we got so far         return ans;     }      public static void main(String[] args)     {         int[][] mat = { { 1, 1, 1, 1 },                         { 1, 1, 0, 1 },                         { 1, 1, 1, 1 } };          // Find the longest path with source (0, 0) and         // destination (2, 3)         int result             = findLongestPath(mat, 0, 0, 2, 3, mat.length,                               mat[0].length, 0, -1);         System.out.println(result);     } } 
Python3
# Function for finding the longest path # 'ans' is -1 if we can't reach # 'cur' is the number of steps we have traversed   def findLongestPath(mat, i, j, di, dj, n, m, cur=0, ans=-1):     # If we reach the destination     if i == di and j == dj:         # If current path steps are more than previous path steps         if cur > ans:             ans = cur         return ans      # if the source or destination is a hurdle itself       if mat[i][j]==0 or mat[di][dj]==0:       return ans     # Mark as visited     mat[i][j] = 0      # Checking if we can reach the destination going right     if j != m-1 and mat[i][j+1] > 0:         ans = findLongestPath(mat, i, j+1, di, dj, n, m, cur+1, ans)      # Checking if we can reach the destination going down     if i != n-1 and mat[i+1][j] > 0:         ans = findLongestPath(mat, i+1, j, di, dj, n, m, cur+1, ans)      # Checking if we can reach the destination going left     if j != 0 and mat[i][j-1] > 0:         ans = findLongestPath(mat, i, j-1, di, dj, n, m, cur+1, ans)      # Checking if we can reach the destination going up     if i != 0 and mat[i-1][j] > 0:         ans = findLongestPath(mat, i-1, j, di, dj, n, m, cur+1, ans)      # Marking visited to backtrack     mat[i][j] = 1      # Returning the answer we got so far     return ans   mat = [     [1, 1, 1, 1],     [1, 1, 0, 1],     [1, 1, 1, 1] ]  # Find the longest path with source (0, 0) and destination (2, 3) vis = [[False for _ in mat[0]] for x in mat] print(findLongestPath(mat, 0, 0, 2, 3, len(mat), len(mat[0]))) 
C#
using System;  public class Program {     // Function for finding the longest path     // 'ans' is -1 if we can't reach     // 'cur' is the number of steps we have traversed     public static int FindLongestPath(int[][] mat, int i,                                       int j, int di, int dj,                                       int n, int m,                                       int cur = 0,                                       int ans = -1)     {         // If we reach the destination         if (i == di && j == dj) {             // If current path steps are more than previous             // path steps             if (cur > ans)                 ans = cur;             return ans;         }                //if the source or destination is a hurdle itself           if(mat[i][j]==0 || mat[di][dj]==0) return ans;                // Mark as visited         mat[i][j] = 0;          // Checking if we can reach the destination going         // right         if (j != m - 1 && mat[i][j + 1] > 0)             ans = FindLongestPath(mat, i, j + 1, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going         // down         if (i != n - 1 && mat[i + 1][j] > 0)             ans = FindLongestPath(mat, i + 1, j, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going         // left         if (j != 0 && mat[i][j - 1] > 0)             ans = FindLongestPath(mat, i, j - 1, di, dj, n,                                   m, cur + 1, ans);          // Checking if we can reach the destination going up         if (i != 0 && mat[i - 1][j] > 0)             ans = FindLongestPath(mat, i - 1, j, di, dj, n,                                   m, cur + 1, ans);          // Marking visited to backtrack         mat[i][j] = 1;          // Returning the answer we got so far         return ans;     }      public static void Main(string[] args)     {         int[][] mat             = new int[][] { new int[] { 1, 1, 1, 1 },                             new int[] { 1, 1, 0, 1 },                             new int[] { 1, 1, 1, 1 } };          // Find the longest path with source (0, 0) and         // destination (2, 3)         int result = FindLongestPath(             mat, 0, 0, 2, 3, mat.Length, mat[0].Length);         Console.WriteLine(result);     } } 
JavaScript
// Function for finding the longest path // 'ans' is -1 if we can't reach // 'cur' is the number of steps we have traversed function findLongestPath(mat, i, j, di, dj, n, m, cur = 0, ans = -1) {     // If we reach the destination     if (i === di && j === dj) {         // If current path steps are more than previous path steps         if (cur > ans)             ans = cur;         return ans;     }      //if the source or destination is a hurdle itself       if(mat[i][j]==0 || mat[di][dj]==0) return ans;          // Mark as visited     mat[i][j] = 0;      // Checking if we can reach the destination going right     if (j !== m - 1 && mat[i][j + 1] > 0)         ans = findLongestPath(mat, i, j + 1, di, dj, n, m, cur + 1, ans);      // Checking if we can reach the destination going down     if (i !== n - 1 && mat[i + 1][j] > 0)         ans = findLongestPath(mat, i + 1, j, di, dj, n, m, cur + 1, ans);      // Checking if we can reach the destination going left     if (j !== 0 && mat[i][j - 1] > 0)         ans = findLongestPath(mat, i, j - 1, di, dj, n, m, cur + 1, ans);      // Checking if we can reach the destination going up     if (i !== 0 && mat[i - 1][j] > 0)         ans = findLongestPath(mat, i - 1, j, di, dj, n, m, cur + 1, ans);      // Marking visited to backtrack     mat[i][j] = 1;      // Returning the answer we got so far     return ans; }  const mat = [     [1, 1, 1, 1],     [1, 1, 0, 1],     [1, 1, 1, 1] ];  // Find the longest path with source (0, 0) and destination (2, 3) const result = findLongestPath(mat, 0, 0, 2, 3, mat.length, mat[0].length); console.log(result); 

Output
9

Time Complexity: O(4^N), where N is the number of cells in the matrix. This is because, at each cell, there are four possible directions to explore (right, down, left, up), and the maximum depth of the recursion is N.
Auxiliary Space: O(1)

 


Next Article
Find shortest safe route in a path with landmines

A

aditya.goel
Improve
Article Tags :
  • Backtracking
  • Matrix
  • DSA
Practice Tags :
  • Backtracking
  • Matrix

Similar Reads

    Backtracking Algorithm
    Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution. They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one. It's like solving a puzzle by testing different pi
    4 min read
    Introduction to Backtracking
    Backtracking is like trying different paths, and when you hit a dead end, you backtrack to the last choice and try a different route. In this article, we'll explore the basics of backtracking, how it works, and how it can help solve all sorts of challenging problems. It's like a method for finding t
    7 min read
    Difference between Backtracking and Branch-N-Bound technique
    Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorit
    4 min read
    What is the difference between Backtracking and Recursion?
    What is Recursion?The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function.Real Life ExampleImagine we have a set of boxes, each containing a smaller box. To find an item, we open the outermost box and conti
    4 min read

    Standard problems on backtracking

    The Knight's tour problem
    Given an n × n chessboard with a Knight starting at the top-left corner (position (0, 0)). The task is to determine a valid Knight's Tour where where the Knight visits each cell exactly once following the standard L-shaped moves of a Knight in chess.If a valid tour exists, print an n × n grid where
    15+ min read
    Rat in a Maze
    Given an n x n binary matrix representing a maze, where 1 means open and 0 means blocked, a rat starts at (0, 0) and needs to reach (n - 1, n - 1).The rat can move up (U), down (D), left (L), and right (R), but:It cannot visit the same cell more than once.It can only move through cells with value 1.
    9 min read
    N Queen Problem
    Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example,
    15+ min read
    Subset Sum Problem using Backtracking
    Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum =
    8 min read
    M-Coloring Problem
    Given an edges of graph and a number m, the your task is to find weather is possible to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color.ExamplesInput: V = 4, edges[][] = [[0, 1], [0, 2], [0,3], [1, 3], [2, 3]], m = 3Output:
    13 min read
    Hamiltonian Cycle
    Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex.If a graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph is a well-known NP-complet
    12 min read
    Algorithm to Solve Sudoku | Sudoku Solver
    Given an incomplete Sudoku in the form of matrix mat[][] of order 9*9, the task is to complete the Sudoku.A sudoku solution must satisfy all of the following rules:Each of the digits 1-9 must occur exactly once in each row.Each of the digits 1-9 must occur exactly once in each column.Each of the dig
    15+ min read
    Magnet Puzzle
    The puzzle game Magnets involves placing a set of domino-shaped magnets (or electrets or other polarized objects) in a subset of slots on a board so as to satisfy a set of constraints. For example, the puzzle on the left has the solution shown on the right:   Each slot contains either a blank entry
    15+ min read
    Remove Invalid Parentheses
    Given a string str consisting only of lowercase letters and the characters '(' and ')'. Your task is to delete minimum parentheses so that the resulting string is balanced, i.e., every opening parenthesis has a matching closing parenthesis in the correct order, and no extra closing parentheses appea
    15+ min read
    A backtracking approach to generate n bit Gray Codes
    Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2Explanation : 00 - 001 - 111 - 310 - 2Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-
    6 min read
    Permutations of given String
    Given a string s, the task is to return all permutations of a given string in lexicographically sorted order.Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist.Examples:Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA"Input: s = "
    5 min read

    Easy Problems on Backtracking

    Print all subsets of a given Set or Array
    Given an array arr of size n, your task is to print all the subsets of the array in lexicographical order.A subset is any selection of elements from an array, where the order does not matter, and no element appears more than once. It can include any number of elements, from none (the empty subset) t
    12 min read
    Check if a given string is sum-string
    Given a string s, the task is to determine whether it can be classified as a sum-string. A string is a sum-string if it can be split into more than two substring such that, the rightmost substring is equal to the sum of the two substrings immediately before it. This rule must recursively apply to th
    14 min read
    Count all possible Paths between two Vertices
    Given a Directed Graph with n vertices represented as a list of directed edges represented by a 2D array edgeList[][], where each edge is defined as (u, v) meaning there is a directed edge from u to v. Additionally, you are given two vertices: source and destination. The task is to determine the tot
    15+ min read
    Find all distinct subsets of a given set using BitMasking Approach
    Given an array arr[] that may contain duplicates. The task is to return all possible subsets. Return only unique subsets and they can be in any order.Note: The individual subsets should be sorted.Examples: Input: arr[] = [1, 2, 2]Output: [], [1], [2], [1, 2], [2, 2], [1, 2, 2]Explanation: The total
    7 min read
    Find if there is a path of more than k weight from a source
    Given an undirected graph represented by the edgeList[][], where each edgeList[i] contains three integers [u, v, w], representing an undirected edge from u to v, having distance w. You are also given a source vertex, and a positive integer k. Your task is to determine if there exist a simple path (w
    10 min read
    Print all paths from a given source to a destination
    Given a directed acyclic graph, a source vertex src and a destination vertex dest, print all paths from given src to dest. Examples:Input: V = 4, edges[ ][ ] = [[0, 1], [1, 2], [1, 3], [2, 3]], src = 0, dest = 3Output: [[0, 1, 2, 3], [0, 1, 3]]Explanation: There are two ways to reach at 3 from 0. Th
    12 min read
    Print all possible strings that can be made by placing spaces
    Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. Input: str[] = "ABC" Output: ABC AB C A BC A B C Source: Amazon Interview Experience | Set 158, Round 1, Q 1. Recommended PracticePermutation with SpacesTry It! The idea is to use
    11 min read

    Medium prblems on Backtracking

    Tug of War
    Given an array arr[] of size n, the task is to divide it into two subsets such that the absolute difference between the sum of elements in the two subsets.If n is even, both subsets must have exactly n/2 elements.If n is odd, one subset must have (n−1)/2 elements and the other must have (n+1)/2 elem
    11 min read
    8 queen problem
    Given an 8x8 chessboard, the task is to place 8 queens on the board such that no 2 queens threaten each other. Return a matrix of size 8x8, where 1 represents queen and 0 represents an empty position. Approach:The idea is to use backtracking to place the queens one by one on the board. Starting from
    9 min read
    Combination Sum
    Given an array of distinct integers arr[] and an integer target, the task is to find a list of all unique combinations of array where the sum of chosen element is equal to target.Note: The same number may be chosen from array an unlimited number of times. Two combinations are unique if the frequency
    8 min read
    Warnsdorff's algorithm for Knight’s tour problem
    Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indica
    15+ min read
    Find paths from corner cell to middle cell in maze
    Given a square maze represented by a matrix mat[][] of positive numbers, the task is to find all paths from all four corner cells to the middle cell. From any cell mat[i][j] with value n, you are allowed to move exactly n steps in one of the four cardinal directions—North, South, East, or West. That
    14 min read
    Maximum number possible by doing at-most K swaps
    Given a string s and an integer k, the task is to find the maximum possible number by performing swap operations on the digits of s at most k times.Examples: Input: s = "7599", k = 2Output: 9975Explanation: Two Swaps can make input 7599 to 9975. First swap 9 with 5 so number becomes 7995, then swap
    15 min read
    Rat in a Maze with multiple steps or jump allowed
    You are given an n × n maze represented as a matrix. The rat starts from the top-left corner (mat[0][0]) and must reach the bottom-right corner (mat[n-1][n-1]).The rat can move forward (right) or downward.A 0 in the matrix represents a dead end, meaning the rat cannot step on that cell.A non-zero va
    11 min read
    N Queen in O(n) space
    Given an integer n, the task is to find the solution to the n-queens problem, where n queens are placed on an n*n chessboard such that no two queens can attack each other.The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.For example, th
    7 min read

    Hard problems on Backtracking

    Power Set in Lexicographic order
    This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last charact
    9 min read
    Word Break Problem using Backtracking
    Given a non-empty sequence s and a dictionary dict[] containing a list of non-empty words, the task is to return all possible ways to break the sentence in individual dictionary words.Note: The same word in the dictionary may be reused multiple times while breaking.Examples: Input: s = “catsanddog”
    8 min read
    Partition of a set into K subsets with equal sum
    Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset.Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
    9 min read
    Longest Possible Route in a Matrix with Hurdles
    Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of the longest possible route possible from source to a destination within the matrix. We are allowed to move to only adjacent cells which are not hurdles. The route cannot contain any diagonal moves and a location on
    15+ min read
    Find shortest safe route in a path with landmines
    Given a path in the form of a rectangular matrix having few landmines arbitrarily placed (marked as 0), calculate length of the shortest safe route possible from any cell in the first column to any cell in the last column of the matrix. We have to avoid landmines and their four adjacent cells (left,
    15+ min read
    Printing all solutions in N-Queen Problem
    Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an n * n chessboard such that no two queens can attack each other. Note: Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The numbe
    15+ min read
    Print all longest common sub-sequences in lexicographical order
    You are given two strings, the task is to print all the longest common sub-sequences in lexicographical order. Examples: Input : str1 = "abcabcaa", str2 = "acbacba" Output: ababa abaca abcba acaba acaca acbaa acbcaRecommended PracticePrint all LCS sequencesTry It! This problem is an extension of lon
    14 min read
    Top 20 Backtracking Algorithm Interview Questions
    Backtracking is a powerful algorithmic technique used to solve problems by exploring all possible solutions in a systematic and recursive manner. It is particularly useful for problems that require searching through a vast solution space, such as combinatorial problems, constraint satisfaction probl
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences