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:
Printing all solutions in N-Queen Problem
Next article icon

Find shortest safe route in a path with landmines

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

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, right, above and below) as they are also unsafe. We are allowed to move to only adjacent cells which are not landmines. i.e. the route cannot contains any diagonal moves.

Examples:  

Input: 
A 12 x 10 matrix with landmines marked as 0[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]
[ 1 1 1 1 0 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 0 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 0 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 0 1 1 1 1 0 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]Output:
Length of shortest safe route is 13 (Highlighted in Bold)

The idea is to use Backtracking. We first mark all adjacent cells of the landmines as unsafe. Then for each safe cell of first column of the matrix, we move forward in all allowed directions and recursively checks if they leads to the destination or not. If destination is found, we update the value of shortest path else if none of the above solutions work we return false from our function.

Below is the implementation of above idea:

C++
// C++ program to find shortest safe Route in // the matrix with landmines #include <bits/stdc++.h> using namespace std; #define R 12 #define C 10  // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNum[] = { -1, 0, 0, 1 }; int colNum[] = { 0, -1, 1, 0 };  // A function to check if a given cell (x, y) // can be visited or not bool isSafe(int mat[R][C], int visited[R][C],             int x, int y) {     if (mat[x][y] == 0 || visited[x][y])         return false;      return true; }  // A function to check if a given cell (x, y) is // a valid cell or not bool isValid(int x, int y) {     if (x < R && y < C && x >= 0 && y >= 0)         return true;      return false; }  // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 void markUnsafeCells(int mat[R][C]) {     for (int i = 0; i < R; i++)     {         for (int j = 0; j < C; j++)         {             // if a landmines is found             if (mat[i][j] == 0)             {               // mark all adjacent cells               for (int k = 0; k < 4; k++)                 if (isValid(i + rowNum[k], j + colNum[k]))                     mat[i + rowNum[k]][j + colNum[k]] = -1;             }         }     }      // mark all found adjacent cells as unsafe     for (int i = 0; i < R; i++)     {         for (int j = 0; j < C; j++)         {             if (mat[i][j] == -1)                 mat[i][j] = 0;         }     }      // Uncomment below lines to print the path     /*for (int i = 0; i < R; i++)     {         for (int j = 0; j < C; j++)         {             cout << std::setw(3) << mat[i][j];         }         cout << endl;     }*/ }  // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost void findShortestPathUtil(int mat[R][C], int visited[R][C],                           int i, int j, int &min_dist, int dist) {     // if destination is reached     if (j == C-1)     {         // update shortest path found so far         min_dist = min(dist, min_dist);         return;     }      // if current path cost exceeds minimum so far     if (dist > min_dist)         return;      // include (i, j) in current path     visited[i][j] = 1;      // Recurse for all safe adjacent neighbours     for (int k = 0; k < 4; k++)     {         if (isValid(i + rowNum[k], j + colNum[k]) &&             isSafe(mat, visited, i + rowNum[k], j + colNum[k]))         {             findShortestPathUtil(mat, visited, i + rowNum[k],                            j + colNum[k], min_dist, dist + 1);         }     }      // Backtrack     visited[i][j] = 0; }  // A wrapper function over findshortestPathUtil() void findShortestPath(int mat[R][C]) {     // stores minimum cost of shortest path so far     int min_dist = INT_MAX;      // create a boolean matrix to store info about     // cells already visited in current route     int visited[R][C];      // mark adjacent cells of landmines as unsafe     markUnsafeCells(mat);      // start from first column and take minimum     for (int i = 0; i < R; i++)     {         // if path is safe from current cell         if (mat[i][0] == 1)         {             // initialize visited to false             memset(visited, 0, sizeof visited);              // find shortest route from (i, 0) to any             // cell of last column (x, C - 1) where             // 0 <= x < R             findShortestPathUtil(mat, visited, i, 0,                                  min_dist, 0);              // if min distance is already found             if(min_dist == C - 1)                 break;         }     }      // if destination can be reached     if (min_dist != INT_MAX)         cout << "Length of shortest safe route is "              << min_dist;      else // if the destination is not reachable         cout << "Destination not reachable from "              << "given source"; }  // Driver code int main() {     // input matrix with landmines shown with number 0     int mat[R][C] =     {         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },         { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }     };      // find shortest path     findShortestPath(mat);      return 0; } 
Java
// Java program to find shortest safe Route // in the matrix with landmines import java.util.Arrays;  class GFG{  static final int R = 12; static final int C = 10;  // These arrays are used to get row and column // numbers of 4 neighbours of a given cell static int rowNum[] = { -1, 0, 0, 1 }; static int colNum[] = { 0, -1, 1, 0 };  static int min_dist;  // A function to check if a given cell (x, y) // can be visited or not static boolean isSafe(int[][] mat, boolean[][] visited,                       int x, int y)  {     if (mat[x][y] == 0 || visited[x][y])         return false;      return true; }  // A function to check if a given cell (x, y) is // a valid cell or not static boolean isValid(int x, int y) {     if (x < R && y < C && x >= 0 && y >= 0)         return true;      return false; }  // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 static void markUnsafeCells(int[][] mat) {     for(int i = 0; i < R; i++)      {         for(int j = 0; j < C; j++)          {                          // If a landmines is found             if (mat[i][j] == 0)              {                                  // Mark all adjacent cells                 for(int k = 0; k < 4; k++)                     if (isValid(i + rowNum[k], j + colNum[k]))                         mat[i + rowNum[k]][j + colNum[k]] = -1;             }         }     }      // Mark all found adjacent cells as unsafe     for(int i = 0; i < R; i++)      {         for(int j = 0; j < C; j++)          {             if (mat[i][j] == -1)                 mat[i][j] = 0;         }     }      // Uncomment below lines to print the path     /*      * for (int i = 0; i < R; i++) {      * for (int j = 0; j < C; j++) { cout <<      * std::setw(3) << mat[i][j]; } cout << endl; }      */ }  // Function to find shortest safe Route in the // matrix with landmines // mat[][] - binary input matrix with safe cells marked as 1 // visited[][] - store info about cells already visited in // current route // (i, j) are coordinates of the current cell // min_dist --> stores minimum cost of shortest path so far // dist --> stores current path cost static void findShortestPathUtil(int[][] mat,                                   boolean[][] visited,                                  int i, int j, int dist) {          // If destination is reached     if (j == C - 1)      {                  // Update shortest path found so far         min_dist = Math.min(dist, min_dist);         return;     }          // If current path cost exceeds minimum so far     if (dist > min_dist)         return;      // include (i, j) in current path     visited[i][j] = true;      // Recurse for all safe adjacent neighbours     for(int k = 0; k < 4; k++)      {         if (isValid(i + rowNum[k], j + colNum[k]) &&              isSafe(mat, visited, i + rowNum[k],                                   j + colNum[k]))         {             findShortestPathUtil(mat, visited, i + rowNum[k],                              j + colNum[k], dist + 1);         }     }      // Backtrack     visited[i][j] = false; }  // A wrapper function over findshortestPathUtil() static void findShortestPath(int[][] mat) {          // Stores minimum cost of shortest path so far     min_dist = Integer.MAX_VALUE;          // Create a boolean matrix to store info about     // cells already visited in current route     boolean[][] visited = new boolean[R][C];      // Mark adjacent cells of landmines as unsafe     markUnsafeCells(mat);      // Start from first column and take minimum     for(int i = 0; i < R; i++)      {                  // If path is safe from current cell         if (mat[i][0] == 1)         {                          // Initialize visited to false             for(int k = 0; k < R; k++)             {                 Arrays.fill(visited[k], false);             }              // Find shortest route from (i, 0) to any             // cell of last column (x, C - 1) where             // 0 <= x < R             findShortestPathUtil(mat, visited, i, 0, 0);              // If min distance is already found             if (min_dist == C - 1)                 break;         }     }          // If destination can be reached     if (min_dist != Integer.MAX_VALUE)         System.out.println("Length of shortest " +                            "safe route is " + min_dist);      else              // If the destination is not reachable         System.out.println("Destination not " +                            "reachable from given source"); }  // Driver code public static void main(String[] args) {          // Input matrix with landmines shown with number 0     int[][] mat = {          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },          { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } };      // Find shortest path     findShortestPath(mat); } }  // This code is contributed by sanjeev2552 
Python3
# Python3 program to find shortest safe Route # in the matrix with landmines import sys  R = 12 C = 10  # These arrays are used to get row and column # numbers of 4 neighbours of a given cell rowNum = [ -1, 0, 0, 1 ] colNum = [ 0, -1, 1, 0 ]  min_dist = sys.maxsize  # A function to check if a given cell (x, y) # can be visited or not def isSafe(mat, visited, x, y):      if (mat[x][y] == 0 or visited[x][y]):         return False      return True  # A function to check if a given cell (x, y) is # a valid cell or not def isValid(x, y):      if (x < R and y < C and x >= 0 and y >= 0):         return True      return False  # A function to mark all adjacent cells of # landmines as unsafe. Landmines are shown with # number 0 def markUnsafeCells(mat):      for i in range(R):         for j in range(C):             # If a landmines is found             if (mat[i][j] == 0):                 # Mark all adjacent cells                 for k in range(4):                     if (isValid(i + rowNum[k], j + colNum[k])):                         mat[i + rowNum[k]][j + colNum[k]] = -1      # Mark all found adjacent cells as unsafe     for i in range(R):         for j in range(C):             if (mat[i][j] == -1):                 mat[i][j] = 0      """ Uncomment below lines to print the path     /*      * for (int i = 0; i < R; i++) {      * for (int j = 0; j < C; j++) { cout <<      * std::setw(3) << mat[i][j]; } cout << endl; }      *"""  # Function to find shortest safe Route in the # matrix with landmines # mat[][] - binary input matrix with safe cells marked as 1 # visited[][] - store info about cells already visited in # current route # (i, j) are coordinates of the current cell # min_dist --> stores minimum cost of shortest path so far # dist --> stores current path cost def findShortestPathUtil(mat, visited, i, j, dist):          global min_dist      # If destination is reached     if (j == C - 1):         # Update shortest path found so far         min_dist = min(dist, min_dist)         return      # If current path cost exceeds minimum so far     if (dist > min_dist):         return      # include (i, j) in current path     visited[i][j] = True      # Recurse for all safe adjacent neighbours     for k in range(4):         if (isValid(i + rowNum[k], j + colNum[k]) and isSafe(mat, visited, i + rowNum[k], j + colNum[k])):             findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1)      # Backtrack     visited[i][j] = False  # A wrapper function over findshortestPathUtil() def findShortestPath(mat):          global min_dist      # Stores minimum cost of shortest path so far     min_dist = sys.maxsize      # Create a boolean matrix to store info about     # cells already visited in current route     visited = [[False for i in range(C)] for j in range(R)]      # Mark adjacent cells of landmines as unsafe     markUnsafeCells(mat)      # Start from first column and take minimum     for i in range(R):         # If path is safe from current cell         if (mat[i][0] == 1):             # Find shortest route from (i, 0) to any             # cell of last column (x, C - 1) where             # 0 <= x < R             findShortestPathUtil(mat, visited, i, 0, 0)              # If min distance is already found             if (min_dist == C - 1):                 break      # If destination can be reached     if (min_dist != sys.maxsize):         print("Length of shortest safe route is", min_dist)     else:         # If the destination is not reachable         print("Destination not reachable from given source")          mat = [         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ]    # Find shortest path findShortestPath(mat)  # This code is contributed by mukesh07. 
C#
// C# program to find shortest safe Route // in the matrix with landmines using System; using System.Collections.Generic; class GFG {          static int R = 12;     static int C = 10;           // These arrays are used to get row and column     // numbers of 4 neighbours of a given cell     static int[] rowNum = { -1, 0, 0, 1 };     static int[] colNum = { 0, -1, 1, 0 };           static int min_dist;           // A function to check if a given cell (x, y)     // can be visited or not     static bool isSafe(int[,] mat, bool[,] visited, int x, int y)     {         if (mat[x,y] == 0 || visited[x,y])             return false;               return true;     }           // A function to check if a given cell (x, y) is     // a valid cell or not     static bool isValid(int x, int y)     {         if (x < R && y < C && x >= 0 && y >= 0)             return true;               return false;     }           // A function to mark all adjacent cells of     // landmines as unsafe. Landmines are shown with     // number 0     static void markUnsafeCells(int[,] mat)     {         for(int i = 0; i < R; i++)         {             for(int j = 0; j < C; j++)             {                                   // If a landmines is found                 if (mat[i,j] == 0)                 {                                           // Mark all adjacent cells                     for(int k = 0; k < 4; k++)                         if (isValid(i + rowNum[k], j + colNum[k]))                             mat[i + rowNum[k],j + colNum[k]] = -1;                 }             }         }               // Mark all found adjacent cells as unsafe         for(int i = 0; i < R; i++)         {             for(int j = 0; j < C; j++)             {                 if (mat[i,j] == -1)                     mat[i,j] = 0;             }         }               // Uncomment below lines to print the path         /*          * for (int i = 0; i < R; i++) {          * for (int j = 0; j < C; j++) { cout <<          * std::setw(3) << mat[i][j]; } cout << endl; }          */     }           // Function to find shortest safe Route in the     // matrix with landmines     // mat[][] - binary input matrix with safe cells marked as 1     // visited[][] - store info about cells already visited in     // current route     // (i, j) are coordinates of the current cell     // min_dist --> stores minimum cost of shortest path so far     // dist --> stores current path cost     static void findShortestPathUtil(int[,] mat,                                      bool[,] visited,                                      int i, int j, int dist)     {                   // If destination is reached         if (j == C - 1)         {                           // Update shortest path found so far             min_dist = Math.Min(dist, min_dist);             return;         }                   // If current path cost exceeds minimum so far         if (dist > min_dist)             return;               // include (i, j) in current path         visited[i,j] = true;               // Recurse for all safe adjacent neighbours         for(int k = 0; k < 4; k++)         {             if (isValid(i + rowNum[k], j + colNum[k]) &&                 isSafe(mat, visited, i + rowNum[k], j + colNum[k]))             {                 findShortestPathUtil(mat, visited, i + rowNum[k], j + colNum[k], dist + 1);             }         }               // Backtrack         visited[i,j] = false;     }           // A wrapper function over findshortestPathUtil()     static void findShortestPath(int[,] mat)     {                   // Stores minimum cost of shortest path so far         min_dist = Int32.MaxValue;                   // Create a boolean matrix to store info about         // cells already visited in current route         bool[,] visited = new bool[R,C];               // Mark adjacent cells of landmines as unsafe         markUnsafeCells(mat);               // Start from first column and take minimum         for(int i = 0; i < R; i++)         {                           // If path is safe from current cell             if (mat[i,0] == 1)             {                 // Find shortest route from (i, 0) to any                 // cell of last column (x, C - 1) where                 // 0 <= x < R                 findShortestPathUtil(mat, visited, i, 0, 0);                       // If min distance is already found                 if (min_dist == C - 1)                     break;             }         }                   // If destination can be reached         if (min_dist != Int32.MaxValue)             Console.WriteLine("Length of shortest " +                                "safe route is " + min_dist);               else                       // If the destination is not reachable             Console.WriteLine("Destination not " +                                "reachable from given source");     }        static void Main()   {          // Input matrix with landmines shown with number 0     int[,] mat = {         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },         { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } };       // Find shortest path     findShortestPath(mat);   } }  // This code is contributed by rameshtravel07. 
JavaScript
<script>     // Javascript program to find shortest safe Route     // in the matrix with landmines          let R = 12;     let C = 10;      // These arrays are used to get row and column     // numbers of 4 neighbours of a given cell     let rowNum = [ -1, 0, 0, 1 ];     let colNum = [ 0, -1, 1, 0 ];      let min_dist;      // A function to check if a given cell (x, y)     // can be visited or not     function isSafe(mat, visited, x, y)     {         if (mat[x][y] == 0 || visited[x][y])             return false;          return true;     }      // A function to check if a given cell (x, y) is     // a valid cell or not     function isValid(x, y)     {         if (x < R && y < C && x >= 0 && y >= 0)             return true;          return false;     }      // A function to mark all adjacent cells of     // landmines as unsafe. Landmines are shown with     // number 0     function markUnsafeCells(mat)     {         for(let i = 0; i < R; i++)         {             for(let j = 0; j < C; j++)             {                  // If a landmines is found                 if (mat[i][j] == 0)                 {                      // Mark all adjacent cells                     for(let k = 0; k < 4; k++)                         if (isValid(i + rowNum[k], j + colNum[k]))                             mat[i + rowNum[k]][j + colNum[k]] = -1;                 }             }         }          // Mark all found adjacent cells as unsafe         for(let i = 0; i < R; i++)         {             for(let j = 0; j < C; j++)             {                 if (mat[i][j] == -1)                     mat[i][j] = 0;             }         }          // Uncomment below lines to print the path         /*          * for (int i = 0; i < R; i++) {          * for (int j = 0; j < C; j++) { cout <<          * std::setw(3) << mat[i][j]; } cout << endl; }          */     }      // Function to find shortest safe Route in the     // matrix with landmines     // mat[][] - binary input matrix with safe cells marked as 1     // visited[][] - store info about cells already visited in     // current route     // (i, j) are coordinates of the current cell     // min_dist --> stores minimum cost of shortest path so far     // dist --> stores current path cost     function findShortestPathUtil(mat, visited, i, j, dist)     {          // If destination is reached         if (j == C - 1)         {              // Update shortest path found so far             min_dist = Math.min(dist, min_dist);             return;         }          // If current path cost exceeds minimum so far         if (dist > min_dist)             return;          // include (i, j) in current path         visited[i][j] = true;          // Recurse for all safe adjacent neighbours         for(let k = 0; k < 4; k++)         {             if (isValid(i + rowNum[k], j + colNum[k]) &&                 isSafe(mat, visited, i + rowNum[k],                                      j + colNum[k]))             {                 findShortestPathUtil(mat, visited, i + rowNum[k],                                  j + colNum[k], dist + 1);             }         }          // Backtrack         visited[i][j] = false;     }      // A wrapper function over findshortestPathUtil()     function findShortestPath(mat)     {          // Stores minimum cost of shortest path so far         min_dist = Number.MAX_VALUE;          // Create a boolean matrix to store info about         // cells already visited in current route         let visited = new Array(R);                  for(let i = 0; i < R; i++)         {             visited[i] = new Array(C);             for(let j = 0; j < C; j++)             {                 visited[i][j] = false;             }         }          // Mark adjacent cells of landmines as unsafe         markUnsafeCells(mat);          // Start from first column and take minimum         for(let i = 0; i < R; i++)         {             // If path is safe from current cell             if (mat[i][0] == 1)             {                  // Find shortest route from (i, 0) to any                 // cell of last column (x, C - 1) where                 // 0 <= x < R                 findShortestPathUtil(mat, visited, i, 0, 0);                  // If min distance is already found                 if (min_dist == C - 1)                     break;             }         }          // If destination can be reached         if (min_dist != Number.MAX_VALUE)             document.write("Length of shortest " +                                "safe route is " + min_dist + "</br>");          else              // If the destination is not reachable             document.write("Destination not " +                                "reachable from given source" + "</br>");     }          // Input matrix with landmines shown with number 0     let mat = [         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ];       // Find shortest path     findShortestPath(mat);  // This code is contributed by decode2207. </script> 

Output
Length of shortest safe route is 13 

Time Complexity: O(4^(R * C)), where R is number of rows and C are the number of columns in the given matrix.
Auxiliary Space: O(R * C), as we are using extra space like visted[R][C].

Another method: It can be solved in polynomial time with the help of Breadth First Search. Enqueue the cells with 1 value in the queue with the distance as 0. As the BFS proceeds, shortest path to each cell from the first column is computed. Finally for the reachable cells in the last column, output the minimum distance.

The implementation in C++ is as follows: 

C++
// C++ program to find shortest safe Route in // the matrix with landmines #include <bits/stdc++.h> using namespace std;  #define R 12  #define C 10   struct Key{     int x,y;     Key(int i,int j){ x=i;y=j;}; };  // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNum[] = { -1, 0, 0, 1 };  int colNum[] = { 0, -1, 1, 0 };  // A function to check if a given cell (x, y) is // a valid cell or not bool isValid(int x, int y)  {      if (x < R && y < C && x >= 0 && y >= 0)          return true;       return false;  }   // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 void findShortestPath(int mat[R][C]){     int i,j;      for (i = 0; i < R; i++)      {          for (j = 0; j < C; j++)          {              // if a landmines is found             if (mat[i][j] == 0)              {              // mark all adjacent cells             for (int k = 0; k < 4; k++)                  if (isValid(i + rowNum[k], j + colNum[k]))                      mat[i + rowNum[k]][j + colNum[k]] = -1;              }          }      }  // mark all found adjacent cells as unsafe     for (i = 0; i < R; i++)      {          for (j = 0; j < C; j++)          {              if (mat[i][j] == -1)                  mat[i][j] = 0;          }      }       int dist[R][C];      for(i=0;i<R;i++){         for(j=0;j<C;j++)             dist[i][j] = -1;     }     queue<Key> q;      for(i=0;i<R;i++){         if(mat[i][0] == 1){             q.push(Key(i,0));             dist[i][0] = 0;         }     }      while(!q.empty()){         Key k = q.front();         q.pop();          int d = dist[k.x][k.y];          int x = k.x;         int y = k.y;          for (int k = 0; k < 4; k++) {             int xp = x + rowNum[k];             int yp = y + colNum[k];             if(isValid(xp,yp) && dist[xp][yp] == -1 && mat[xp][yp] == 1){                 dist[xp][yp] = d+1;                 q.push(Key(xp,yp));             }         }     }     // stores minimum cost of shortest path so far     int ans = INT_MAX;     // start from first column and take minimum     for(i=0;i<R;i++){         if(mat[i][C-1] == 1 && dist[i][C-1] != -1){             ans = min(ans,dist[i][C-1]);         }     }          // if destination can be reached     if(ans == INT_MAX)         cout << "NOT POSSIBLE\n";              else// if the destination is not reachable         cout << "Length of shortest safe route is " << ans << endl; }  // Driver code int main(){          // input matrix with landmines shown with number 0     int mat[R][C] =      {          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },          { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },          { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },          { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }      };           // find shortest path     findShortestPath(mat);  } 
Java
// Java program to find shortest safe Route in // the matrix with landmines  import java.util.LinkedList; import java.util.Queue;  public class GFG {      static class Key {         int x, y;         Key(int i, int j)         {             x = i;             y = j;         };     }      static int R = 12, C = 10;     // These arrays are used to get row and column     // numbers of 4 neighbours of a given cell     static int rowNum[] = { -1, 0, 0, 1 };     static int colNum[] = { 0, -1, 1, 0 };      // A function to check if a given cell (x, y) is     // a valid cell or not     static boolean isValid(int x, int y)     {         if (x < R && y < C && x >= 0 && y >= 0)             return true;          return false;     }      // A function to mark all adjacent cells of     // landmines as unsafe. Landmines are shown with     // number 0     static void findShortestPath(int mat[][])     {         int i, j;          for (i = 0; i < R; i++) {             for (j = 0; j < C; j++) {                 // if a landmines is found                 if (mat[i][j] == 0) {                     // mark all adjacent cells                     for (int k = 0; k < 4; k++)                         if (isValid(i + rowNum[k],                                     j + colNum[k]))                             mat[i + rowNum[k]]                                [j + colNum[k]]                                 = -1;                 }             }         }         // mark all found adjacent cells as unsafe         for (i = 0; i < R; i++) {             for (j = 0; j < C; j++) {                 if (mat[i][j] == -1)                     mat[i][j] = 0;             }         }          int dist[][] = new int[R][C];          for (i = 0; i < R; i++) {             for (j = 0; j < C; j++)                 dist[i][j] = -1;         }         Queue<Key> q = new LinkedList<Key>();          for (i = 0; i < R; i++) {             if (mat[i][0] == 1) {                 q.add(new Key(i, 0));                 dist[i][0] = 0;             }         }          while (!q.isEmpty()) {             Key k = q.peek();             q.poll();              int d = dist[k.x][k.y];              int x = k.x;             int y = k.y;              for (int ki = 0; ki < 4; ki++) {                 int xp = x + rowNum[ki];                 int yp = y + colNum[ki];                 if (isValid(xp, yp) && dist[xp][yp] == -1                     && mat[xp][yp] == 1) {                     dist[xp][yp] = d + 1;                     q.add(new Key(xp, yp));                 }             }         }         // stores minimum cost of shortest path so far         int ans = Integer.MAX_VALUE;         // start from first column and take minimum         for (i = 0; i < R; i++) {             if (mat[i][C - 1] == 1                 && dist[i][C - 1] != -1) {                 ans = Math.min(ans, dist[i][C - 1]);             }         }          // if destination can be reached         if (ans == Integer.MAX_VALUE)             System.out.println("NOT POSSIBLE");          else // if the destination is not reachable             System.out.println(                 "Length of shortest safe route is " + ans);     }      // Driver code     public static void main(String[] args)     {          // input matrix with landmines shown with number 0         int mat[][] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },                         { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } };          // find shortest path         findShortestPath(mat);     } }  // This code is contributed by Lovely Jain 
Python3
# Python program to find shortest safe Route in # the matrix with landmines import sys  R = 12 C = 10  class Key:     def __init__(self,i, j):         self.x = i         self.y = j  # These arrays are used to get row and column # numbers of 4 neighbours of a given cell rowNum = [ -1, 0, 0, 1 ] colNum = [ 0, -1, 1, 0 ]  # A function to check if a given cell (x, y) is # a valid cell or not def isValid(x, y):      if (x < R and y < C and x >= 0 and y >= 0):         return True      return False  # A function to mark all adjacent cells of # landmines as unsafe. Landmines are shown with # number 0 def findShortestPath(mat):      for i in range(R):         for j in range(C):             # if a landmines is found             if (mat[i][j] == 0):                 # mark all adjacent cells                 for k in range(4):                     if (isValid(i + rowNum[k], j + colNum[k])):                         mat[i + rowNum[k]][j + colNum[k]] = -1                  # mark all found adjacent cells as unsafe     for i in range(R):         for j in range(C):             if (mat[i][j] == -1):                 mat[i][j] = 0      dist = [[-1 for i in range(C)]for j in range(R)]      q = []      for i in range(R):         if(mat[i][0] == 1):             q.append(Key(i,0))             dist[i][0] = 0      while(len(q) != 0):         k = q[0]         q = q[1:]          d = dist[k.x][k.y]          x = k.x         y = k.y          for k in range(4):             xp = x + rowNum[k]             yp = y + colNum[k]             if(isValid(xp,yp) and dist[xp][yp] == -1 and mat[xp][yp] == 1):                 dist[xp][yp] = d+1                 q.append(Key(xp,yp))          # stores minimum cost of shortest path so far     ans = sys.maxsize      # start from first column and take minimum     for i in range(R):         if(mat[i][C-1] == 1 and dist[i][C-1] != -1):             ans = min(ans,dist[i][C-1])           # if destination can be reached     if(ans == sys.maxsize):         print("NOT POSSIBLE")              else:  # if the destination is not reachable         print(f"Length of shortest safe route is {ans}")  # Driver code      # input matrix with landmines shown with number 0 mat =[         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ]      # find shortest path findShortestPath(mat)  # This code is contributed by shinjanpatra 
C#
// C# program to find shortest safe Route in // the matrix with landmines using System; using System.Collections.Generic;  class Key {     public int x, y;     public Key(int i, int j)     {         x = i;         y = j;     } }  public class GFG {            static int R = 12, C = 10;     // These arrays are used to get row and column     // numbers of 4 neighbours of a given cell     static int[] rowNum = { -1, 0, 0, 1 };     static int[] colNum = { 0, -1, 1, 0 };      // A function to check if a given cell (x, y) is     // a valid cell or not     static bool isValid(int x, int y)     {         if (x < R && y < C && x >= 0 && y >= 0)             return true;          return false;     }      // A function to mark all adjacent cells of     // landmines as unsafe. Landmines are shown with     // number 0     static void findShortestPath(int[, ] mat)     {         int i, j;          for (i = 0; i < R; i++) {             for (j = 0; j < C; j++) {                 // if a landmines is found                 if (mat[i, j] == 0) {                     // mark all adjacent cells                     for (int k = 0; k < 4; k++)                         if (isValid(i + rowNum[k],                                     j + colNum[k]))                             mat[i + rowNum[k], j + colNum[k]]                                 = -1;                 }             }         }         // mark all found adjacent cells as unsafe         for (i = 0; i < R; i++) {             for (j = 0; j < C; j++) {                 if (mat[i, j] == -1)                     mat[i, j] = 0;             }         }          int[, ] dist = new int[R, C];          for (i = 0; i < R; i++) {             for (j = 0; j < C; j++)                 dist[i, j] = -1;         }         List<Key> q = new List<Key>();          for (i = 0; i < R; i++) {             if (mat[i, 0] == 1) {                 q.Add(new Key(i, 0));                 dist[i, 0] = 0;             }         }          while (q.Count != 0) {             Key k = q[0];             q.RemoveAt(0);              int d = dist[k.x, k.y];              int x = k.x;             int y = k.y;              for (int ki = 0; ki < 4; ki++) {                 int xp = x + rowNum[ki];                 int yp = y + colNum[ki];                 if (isValid(xp, yp) && dist[xp, yp] == -1                     && mat[xp, yp] == 1) {                     dist[xp, yp] = d + 1;                     q.Add(new Key(xp, yp));                 }             }         }         // stores minimum cost of shortest path so far         int ans = Int32.MaxValue;         // start from first column and take minimum         for (i = 0; i < R; i++) {             if (mat[i, C - 1] == 1                 && dist[i, C - 1] != -1) {                 ans = Math.Min(ans, dist[i, C - 1]);             }         }          // if destination can be reached         if (ans == Int32.MaxValue)             Console.WriteLine("NOT POSSIBLE");          else // if the destination is not reachable             Console.WriteLine(                 "Length of shortest safe route is " + ans);     }      // Driver code     public static void Main(string[] args)     {          // input matrix with landmines shown with number 0         int[,] mat = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },                         { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 },                         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },                         { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 } };          // find shortest path         findShortestPath(mat);     } }  // This code is contributed by phasing17 
JavaScript
<script>  // JavaScript program to find shortest safe Route in // the matrix with landmines const R = 12 const C = 10  class Key {     constructor(i, j)     {         this.x = i         this.y = j     } }  // These arrays are used to get row and column // numbers of 4 neighbours of a given cell let rowNum = [ -1, 0, 0, 1 ] let colNum = [ 0, -1, 1, 0 ]  // A function to check if a given cell (x, y) is // a valid cell or not function isValid(x, y) {     if (x < R && y < C && x >= 0 && y >= 0)         return true      return false }  // A function to mark all adjacent cells of // landmines as unsafe. Landmines are shown with // number 0 function findShortestPath(mat){     let i,j      for (i = 0;i < R;i++)     {         for (j = 0;j < C;j++)         {             // if a landmines is found             if (mat[i][j] == 0)             {             // mark all adjacent cells             for (let k = 0;k < 4;k++)                 if (isValid(i + rowNum[k], j + colNum[k]))                     mat[i + rowNum[k]][j + colNum[k]] = -1             }         }     } // mark all found adjacent cells as unsafe     for (i = 0;i < R;i++)     {         for (j = 0;j < C;j++)         {             if (mat[i][j] == -1)                 mat[i][j] = 0         }     }      let dist = new Array(R);      for(i = 0; i < R; i++){         dist[i] = new Array(C).fill(-1);     }     let q = [];      for(i = 0; i < R; i++){         if(mat[i][0] == 1){             q.push(new Key(i,0))             dist[i][0] = 0         }     }      while(q.length != 0){         let k = q.shift()          let d = dist[k.x][k.y]          let x = k.x         let y = k.y          for (let k = 0;k < 4;k++) {             let xp = x + rowNum[k]             let yp = y + colNum[k]             if(isValid(xp,yp) && dist[xp][yp] == -1 && mat[xp][yp] == 1){                 dist[xp][yp] = d+1                 q.push(new Key(xp,yp))             }         }     }          // stores minimum cost of shortest path so far     let ans = Number.MAX_VALUE          // start from first column and take minimum     for(let i = 0; i < R; i++)     {         if(mat[i][C-1] == 1 && dist[i][C-1] != -1){             ans = Math.min(ans,dist[i][C-1])         }     }          // if destination can be reached     if(ans == Number.MAX_VALUE)         document.write("NOT POSSIBLE","</br>")              else  // if the destination is not reachable         document.write("Length of shortest safe route is ",ans,"</br>") }  // Driver code      // input matrix with landmines shown with number 0 let mat =[         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 0, 1, 1, 1, 1, 0, 1, 1, 1, 1 ],         [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],         [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ] ]      // find shortest path findShortestPath(mat)  // This code is contributed by shinjanpatra  </script> 

Output
Length of shortest safe route is 13 

Time Complexity: O(r * c), where r and c are the number of rows and columns in the given matrix respectively.
Auxiliary Space: O(r * c)
 


Next Article
Printing all solutions in N-Queen Problem

A

Aditya Goel
Improve
Article Tags :
  • Backtracking
  • Matrix
  • DSA
  • Shortest Path
Practice Tags :
  • Backtracking
  • Matrix
  • Shortest Path

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