The Wayback Machine - https://web.archive.org/web/20240623125120/https://www.geeksforgeeks.org/geek-in-a-maze/
Open In App

Geek in a Maze

Last Updated : 08 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Geek is in a maze of size N * M. Each cell in the maze is made of either ‘.’ or ‘#’. An empty cell is represented by ‘.’ and an obstacle is represented by ‘#’. The task is to find out how many different empty cells he can pass through If Geek starts at cell (R, C) and avoids the obstacles and he can move in any of the four directions but he can move up at most U times and he can move down at most D times. 

Examples:

Input: N = 3, M = 3, 
R = 1, C = 0
U = 1, D = 1
mat = {{. . .}, {. # .}, {# . .}}
Output: 5
Explanation: Geek can reach 
(1, 0), (0, 0), (0, 1), (0, 2), (1, 2) 

Input: N = 3, M = 4, R = 1, C = 0, U = 1, D = 2 
mat = {{. . .},  {. # .}, {. . .}, {# . .}} 
Output: 10
Explanation: Geek can reach all the 
cells except for the obstacles.

 

Brute Force Approach:

Run a simple DFS on matrix and sum all the answers from all branches. Everytime we make a call up or down we will decrement the value of U and D respectively .

In Our Base condition we will also check if we have already visited that cell or not for that we will make cell by ‘#’ when we visit and while returning for un-visiting it we will again mark it as ‘”.” 

Below is implementation of above approach: 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count different empty cells 
// he can pass through while avoiding
// the obstacles
int numberOfCells(int n, int m, int r, int c, int u, int d, vector<vector<char> >& mat)
{
    if(r<0 or c<0 or r>=n or c>=m or u<0 or d<0 or mat[r] == '#')
       return 0;
         
       mat[r] = '#';
       //calls
       int up = numberOfCells(n,m,r-1,c,u-1,d,mat);
       int down = numberOfCells(n,m,r+1,c,u,d-1,mat);
       int left = numberOfCells(n,m,r,c-1,u,d,mat);
       int right = numberOfCells(n,m,r,c+1,u,d,mat);
        
       mat[r] = '.';
       return 1 + up + down + left + right;
}
 
// Driver code
int main()
{
    int N = 3, M = 3, R = 1, C = 0;
    int U = 1, D = 1;
    vector<vector<char> > mat = { { '.', '.', '.' },
                                  { '.', '#', '.' },
                                  { '#', '.', '.' } };
 
    // Function call
    cout << numberOfCells(N, M, R, C, U, D, mat);
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
class GFG {
 
  // Function to count different empty cells 
  // he can pass through while avoiding
  // the obstacles
  static int numberOfCells(int n, int m, int r, int c,int u, int d, char[][] mat){
    if (r < 0 || c < 0 || r >= n || c >= m || u < 0 || d < 0 || mat[r] == '#')
      return 0;
 
    mat[r] = '#';
 
    // calls
    int up = numberOfCells(n, m, r - 1, c, u - 1, d, mat);
    int down = numberOfCells(n, m, r + 1, c, u, d - 1, mat);
    int left = numberOfCells(n, m, r, c - 1, u, d, mat);
    int right = numberOfCells(n, m, r, c + 1, u, d, mat);
 
    mat[r] = '.';
    return 1 + up + down + left + right;
  }
 
  public static void main (String[] args) {
 
    int N = 3, M = 3, R = 1, C = 0;
    int U = 1, D = 1;
    char[][] mat = { { '.', '.', '.' },
                    { '.', '#', '.' },
                    { '#', '.', '.' } };
 
    // Function call
    System.out.println(numberOfCells(N, M, R, C, U, D, mat));
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




def numberOfCells(n, m, r, c, u, d, mat):
    # print(type(mat[r]))
    if(r<0 or c<0 or r>=n or c>=m or u<0 or d<0 or mat[r] == '#'):
        return 0
          
    mat[r] = '#'
 
    up = numberOfCells(n,m,r-1,c,u-1,d,mat)
    down = numberOfCells(n,m,r+1,c,u,d-1,mat)
    left = numberOfCells(n,m,r,c-1,u,d,mat)
    right = numberOfCells(n,m,r,c+1,u,d,mat)
         
    mat[r] = '.'
    return 1 + up + down + left + right
 
 
 
if __name__ == '__main__':
     
    N,M,R,C,U,D = 3,3,1,0,1,1
     
    mat = [['.','.','.'],['.','#','.'],['#','.','.']]
    print(numberOfCells(N, M, R, C, U, D, mat))
 
 # This code is contributed by Arpit Jain


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to count different empty cells 
    // he can pass through while avoiding
    // the obstacles
    static int numberOfCells(int n, int m, int r, int c,
                             int u, int d, char[, ] mat)
    {
        if (r < 0 || c < 0 || r >= n || c >= m || u < 0
            || d < 0 || mat[r, c] == '#')
            return 0;
 
        mat[r, c] = '#';
        // calls
        int up
            = numberOfCells(n, m, r - 1, c, u - 1, d, mat);
        int down
            = numberOfCells(n, m, r + 1, c, u, d - 1, mat);
        int left = numberOfCells(n, m, r, c - 1, u, d, mat);
        int right
            = numberOfCells(n, m, r, c + 1, u, d, mat);
 
        mat[r, c] = '.';
        return 1 + up + down + left + right;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int N = 3, M = 3, R = 1, C = 0;
        int U = 1, D = 1;
        char[, ] mat = { { '.', '.', '.' },
                         { '.', '#', '.' },
                         { '#', '.', '.' } };
 
        // Function call
        Console.WriteLine(
            numberOfCells(N, M, R, C, U, D, mat));
    }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript code to implement the approach
 
 
// Function to count different empty cells 
// he can pass through while avoiding
// the obstacles
function numberOfCells(n, m, r, c, u, d, mat)
{
    if(r<0 || c<0 || r>=n || c>=m || u<00 || d<00 || mat[r] == '#')
       return 0;
         
       //cout<<r<<","<<c<<"\n";
       mat[r] = '#';
       //calls
       let up = numberOfCells(n,m,r-1,c,u-1,d,mat);
       let down = numberOfCells(n,m,r+1,c,u,d-1,mat);
       let left = numberOfCells(n,m,r,c-1,u,d,mat);
       let right = numberOfCells(n,m,r,c+1,u,d,mat);
        
       mat[r] = '.';
       return 1 + up + down + left + right;
}
 
 
// Driver code
let N = 3, M = 3, R = 1, C = 0;
let U = 1, D = 1;
let mat = [ [ '.', '.', '.' ], [ '.', '#', '.' ], [ '#', '.', '.' ] ];
 
// Function call
console.log(numberOfCells(N, M, R, C, U, D, mat));


Output

5

Time Complexity : O(4*(n^m)) since we are making 4 calls for n^m items in a matrix

Space Complexity : O(1) since we are using the same matrix as visited matrix

Efficient Approach: The idea is to solve this problem is based on the following idea:

Keep moving radially in all four directions (up, down, left, right) and keep counting the number of turning taken in moving up and down. If the number of turns left for given upward and downward movements are not 0 then move to up and down and keep counting the empty cells.

Follow the steps mentioned below to implement the idea:

  • Check if the starting point is blocked by an obstacle (#)
    •  If true, return 0.
  • Keep a queue of arrays to store rows, columns, ups, and downs for any cell.
  • Do a BFS traversal:
    • Check if the cell is empty then increment the count variable (say cnt).
    • Check if any up move is left or not.
      • If moves for up is left then move to up and decrement the move count for up and push the current status of the cell in the queue.
    • Check if any down move is left or not.
      • If moves for down is left then move to down and decrement the move count for down and push the current status of the cell in the queue.
  • Finally, return the cnt.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count different empty cells 
// he can pass through while avoiding
// the obstacles
int numberOfCells(int n, int m, int r,
                  int c, int u, int d,
                  vector<vector<char> >& mat)
{
    // If cell having Obstacle
    if (mat[r] == '#')
        return 0;
 
    queue<vector<int> > que;
    int cnt = 0;
    int i = 0;
    int j = 0;
 
    mat[r] = '#';
    que.push({ r, c, u, d });
 
    // BFS traversal of the matrix
    while (que.size()) {
        auto& f = que.front();
        int rr = f[0];
        int cc = f[1];
        int uu = f[2];
        int dd = f[3];
        que.pop();
 
        ++cnt;
 
        // Move left
        i = rr;
        j = cc - 1;
        if (0 <= j && mat[i][j] == '.') {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push({ i, j, uu, dd });
        }
 
        // Move right
        i = rr;
        j = cc + 1;
        if (j < m && mat[i][j] == '.') {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push({ i, j, uu, dd });
        }
 
        // Move up
        i = rr - 1;
        j = cc;
        if (0 <= i && mat[i][j] == '.' && uu) {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push({ i, j, uu - 1, dd });
        }
 
        // Move down
        i = rr + 1;
        j = cc;
        if (i < n && mat[i][j] == '.' && dd) {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push({ i, j, uu, dd - 1 });
        }
    }
 
    // Return the count
    return cnt;
}
 
// Driver code
int main()
{
    int N = 3, M = 3, R = 1, C = 0;
    int U = 1, D = 1;
    vector<vector<char> > mat = { { '.', '.', '.' },
                                  { '.', '#', '.' },
                                  { '#', '.', '.' } };
 
    // Function call
    cout << numberOfCells(N, M, R, C, U, D, mat);
    return 0;
}


Java




import java.util.*;
import java.io.*;
 
// Java program for the above approach
class GFG{
 
    // Function to count different empty cells 
    // he can pass through while avoiding
    // the obstacles
    public static int numberOfCells(int n, int m, int r, int c, int u, int d, ArrayList<ArrayList<Character>> mat)
    {
        // If cell having Obstacle
        if (mat.get(r).get(c) == '#')
            return 0;
 
        Queue<ArrayList<Integer>> que = new ArrayDeque<ArrayList<Integer>>();
        int cnt = 0;
        int i = 0;
        int j = 0;
 
        mat.get(r).set(c, '#');
        que.add(new ArrayList<Integer>(List.of(r, c, u, d)));
 
        // BFS traversal of the matrix
        while (!que.isEmpty()) {
            ArrayList<Integer> f = que.peek();
            int rr = f.get(0);
            int cc = f.get(1);
            int uu = f.get(2);
            int dd = f.get(3);
            que.remove();
 
            ++cnt;
 
            // Move left
            i = rr;
            j = cc - 1;
            if (0 <= j && mat.get(i).get(j) == '.') {
 
                // Mark the cell visited
                mat.get(i).set(j, '#');
                que.add(new ArrayList<Integer>(List.of(i, j, uu, dd)));
            }
 
            // Move right
            i = rr;
            j = cc + 1;
            if (j < m && mat.get(i).get(j) == '.') {
 
                // Mark the cell visited
                mat.get(i).set(j, '#');
                que.add(new ArrayList<Integer>(List.of(i, j, uu, dd)));
            }
 
            // Move up
            i = rr - 1;
            j = cc;
            if (0 <= i && mat.get(i).get(j) == '.' && uu > 0) {
 
                // Mark the cell visited
                mat.get(i).set(j, '#');
                que.add(new ArrayList<Integer>(List.of(i, j, uu-1, dd)));
            }
 
            // Move down
            i = rr + 1;
            j = cc;
            if (i < n && mat.get(i).get(j) == '.' && dd > 0) {
 
                // Mark the cell visited
                mat.get(i).set(j, '#');
                que.add(new ArrayList<Integer>(List.of(i, j, uu, dd-1)));
            }
        }
 
        // Return the count
        return cnt;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int N = 3, M = 3, R = 1, C = 0;
        int U = 1, D = 1;
        ArrayList<ArrayList<Character>> mat = new ArrayList<ArrayList<Character>>(
            List.of(new ArrayList<Character>(
                List.of('.', '.', '.')
            ),
            new ArrayList<Character>(
                List.of('.', '#', '.')
            ),
            new ArrayList<Character>(
                List.of('#', '.', '.')
            ))
        );
 
        // Function call
        System.out.println(numberOfCells(N, M, R, C, U, D, mat));
    }
}
 
// This code is contributed by subhamgoyal2014.


Python3




# Python code to implement the approach
 
# Function to count different empty cells 
# he can pass through while avoiding
# the obstacles
def numberOfCells(n, m, r, c, u, d, mat):
 
    # If cell having Obstacle
    if (mat[r] == '#'):
        return 0;
 
    que = [];
    cnt = 0;
    i = 0;
    j = 0;
 
    mat[r] = '#';
    que.append([ r, c, u, d ]);
 
    # BFS traversal of the matrix
    while (len(que) != 0):
        f = que.pop(0)
        rr = f[0];
        cc = f[1];
        uu = f[2];
        dd = f[3];
 
        cnt += 1;
 
        # Move left
        i = rr;
        j = cc - 1;
        if (0 <= j and mat[i][j] == '.'):
 
            # Mark the cell visited
            mat[i][j] = '#';
            que.append([ i, j, uu, dd ]);
         
 
        # Move right
        i = rr;
        j = cc + 1;
        if (j < m and mat[i][j] == '.') :
 
            # Mark the cell visited
            mat[i][j] = '#';
            que.append([ i, j, uu, dd ]);
         
 
        # Move up
        i = rr - 1;
        j = cc;
        if (0 <= i and mat[i][j] == '.' and uu):
 
            # Mark the cell visited
            mat[i][j] = '#';
            que.append([ i, j, uu - 1, dd ]);
         
 
        # Move down
        i = rr + 1;
        j = cc;
        if (i < n and mat[i][j] == '.' and dd) :
 
            # Mark the cell visited
            mat[i][j] = '#';
            que.append([ i, j, uu, dd - 1 ]);
         
    # Return the count
    return cnt;
 
# Driver code
N = 3
M = 3
R = 1
C = 0;
U = 1
D = 1;
mat = [  [ '.', '.', '.' ], [ '.', '#', '.' ], [ '#', '.', '.' ] ];
 
# Function call
print(numberOfCells(N, M, R, C, U, D, mat));
 
# This code is contributed by phasing17


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
 
class GFG{
 
  // Function to count different empty cells 
  // he can pass through while avoiding
  // the obstacles
  public static int numberOfCells(int n, int m, int r,
                                  int c, int u, int d,
                                  char[, ] mat)
  {
    // If cell having Obstacle
    if (mat[r, c] == '#')
      return 0;
 
    List<int[]> que = new List<int[]> ();
    int cnt = 0;
    int i = 0;
    int j = 0;
 
    mat[r, c] = '#';
    que.Add(new[] {r, c, u, d});
 
    // BFS traversal of the matrix
    while (que.Count != 0) {
      int[]  f = que[0];
      int rr = f[0];
      int cc = f[1];
      int uu = f[2];
      int dd = f[3];
      que.RemoveAt(0);
 
      ++cnt;
 
      // Move left
      i = rr;
      j = cc - 1;
      if (0 <= j && mat[i, j] == '.') {
 
        // Mark the cell visited
        mat[i, j] = '#';
        que.Add(new [] {i, j, uu, dd});
      }
 
      // Move right
      i = rr;
      j = cc + 1;
      if (j < m && mat[i, j] == '.') {
 
        // Mark the cell visited
        mat[i, j] = '#';
        que.Add(new [] {i, j, uu, dd});
      }
 
      // Move up
      i = rr - 1;
      j = cc;
      if (0 <= i && mat[i, j] == '.' && uu > 0) {
 
        // Mark the cell visited
        mat[i, j] = '#';
        que.Add(new [] {i, j, uu-1, dd});
      }
 
      // Move down
      i = rr + 1;
      j = cc;
      if (i < n && mat[i, j] == '.' && dd > 0) {
 
        // Mark the cell visited
        mat[i, j] = '#';
        que.Add(new [] {i, j, uu, dd-1});
      }
    }
 
    // Return the count
    return cnt;
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int N = 3, M = 3, R = 1, C = 0;
    int U = 1, D = 1;
    char[, ] mat = new char[, ] { { '.', '.', '.' },
                                 { '.', '#', '.' },
                                 { '#', '.', '.' } };
 
    // Function call
    Console.WriteLine(numberOfCells(N, M, R, C, U, D, mat));
  }
}
 
// This code is contributed by phasing17.


Javascript




// JS code to implement the approach
 
// Function to count different empty cells 
// he can pass through while avoiding
// the obstacles
function numberOfCells(n, m, r, c, u, d, mat)
 
{
    // If cell having Obstacle
    if (mat[r] == '#')
        return 0;
 
    let que = [];
    let cnt = 0;
    let i = 0;
    let j = 0;
 
    mat[r] = '#';
    que.push([ r, c, u, d ]);
 
    // BFS traversal of the matrix
    while (que.length != 0) {
        let f = que.shift();
        let rr = f[0];
        let cc = f[1];
        let uu = f[2];
        let dd = f[3];
 
        ++cnt;
 
        // Move left
        i = rr;
        j = cc - 1;
        if (0 <= j && mat[i][j] == '.') {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push([ i, j, uu, dd ]);
        }
 
        // Move right
        i = rr;
        j = cc + 1;
        if (j < m && mat[i][j] == '.') {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push([ i, j, uu, dd ]);
        }
 
        // Move up
        i = rr - 1;
        j = cc;
        if (0 <= i && mat[i][j] == '.' && uu) {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push([ i, j, uu - 1, dd ]);
        }
 
        // Move down
        i = rr + 1;
        j = cc;
        if (i < n && mat[i][j] == '.' && dd) {
 
            // Mark the cell visited
            mat[i][j] = '#';
            que.push([ i, j, uu, dd - 1 ]);
        }
    }
 
    // Return the count
    return cnt;
}
 
// Driver code
let N = 3, M = 3, R = 1, C = 0;
let U = 1, D = 1;
let mat = [
    [ '.', '.', '.' ], [ '.', '#', '.' ], [ '#', '.', '.' ]
];
 
// Function call
console.log(numberOfCells(N, M, R, C, U, D, mat));
 
// This code is contributed by phasing17


Output

5

Time Complexity: O(N * M)
Auxiliary Space: O(N * M)



Similar Reads

Rat in a Maze | Backtracking using Stack
Prerequisites - Recursion, Backtracking and Stack Data Structure. A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used
15+ min read
A variation of Rat in a Maze : multiple steps or jumps allowed
A variation of rat in a maze. You are given an N * N 2-D matrix shaped maze (let's call it M), there is a rat in the top-left cell i.e. M[0][0] and there is an escape door in the bottom-right cell i.e. M[N-1][N-1]. From each cell M[i][j] (0 ? i ? N-1, 0 ? j ? N-1) the rat can go a number of steps towards its right ( for eg: to M[i][j+ s]), or a num
15 min read
Count number of ways to reach destination in a maze
Given a maze of 0 and -1 cells, the task is to find all the paths from (0, 0) to (n-1, m-1), and every path should pass through at least one cell which contains -1. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. This problem is a variation of the problem published here.Examples: Input: maze[][] = { {0, 0, 0, 0}, {0,
14 min read
Maze With N doors and 1 Key
Given an N * N binary maze where a 0 denotes that the position can be visited and a 1 denotes that the position cannot be visited without a key, the task is to find whether it is possible to visit the bottom-right cell from the top-left cell with only one key along the way. If possible then print "Yes" else print "No". Example: Input: maze[][] = {
14 min read
Random Acyclic Maze Generator with given Entry and Exit point
Given two integers N and M, the task is to generate any N * M sized maze containing only 0 (representing a wall) and 1 (representing an empty space where one can move) with the entry point as P0 and exit point P1 and there is only one path between any two movable positions. Note: P0 and P1 will be marked as 2 and 3 respectively and one can move thr
15+ min read
Rat in a Maze Problem when movement in all possible directions is allowed
Consider a rat placed at (0, 0) in a square matrix m[ ][ ] of order n and has to reach the destination at (n-1, n-1). The task is to find a sorted array of strings denoting all the possible directions which the rat can take to reach the destination at (n-1, n-1). The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (righ
6 min read
Shortest path in a Binary Maze
Given an MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1. Example: Input: mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, {0, 0, 0,
15+ min read
Find paths from corner cell to middle cell in maze
Given a square maze containing positive numbers, find all paths from a corner cell (any of the extreme four corners) to the middle cell. We can move exactly n steps from a cell in 4 directions i.e. North, East, West and South where n is value of the cell, We can move to mat[i+n][j], mat[i-n][j], mat[i][j+n], and mat[i][j-n] from a cell mat[i][j] wh
15+ min read
Possibility of moving out of maze
Given n integers in a maze indicating a number of moves to be made from that position and a string which has "&gt;" and "&lt;" indicating which side to move. The starting position is the first position. Print whether it stays inside the array or moves out of the array. Example: Input : 3 2 1 1 &gt; &gt; &lt; Output: It stays inside forever Explanat
8 min read
Two Rats in a Maze
Given a 2D matrix maze[][], where some cells are blocked, some cells are locked (which the rats can unlock) and some cells are vacant. Given the initial position of two rats, find the minimum number of cells they need to unlock to escape the maze. A rat can escape the maze if it reaches outside the boundary of the maze. Blocked cells are represente
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg