GFG App
Open App
Browser
Continue

# Geek in a Maze

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 ` `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 >& 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 > 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<

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 ` `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 >& mat)` `{` `    ``// If cell having Obstacle` `    ``if` `(mat[r] == ``'#'``)` `        ``return` `0;`   `    ``queue > 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 > 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> mat) ` `    ``{ ` `        ``// If cell having Obstacle ` `        ``if` `(mat.get(r).get(c) == ``'#'``) ` `            ``return` `0``; `   `        ``Queue> que = ``new` `ArrayDeque>();` `        ``int` `cnt = ``0``; ` `        ``int` `i = ``0``; ` `        ``int` `j = ``0``; `   `        ``mat.get(r).set(c, ``'#'``);` `        ``que.add(``new` `ArrayList(List.of(r, c, u, d))); `   `        ``// BFS traversal of the matrix ` `        ``while` `(!que.isEmpty()) { ` `            ``ArrayList 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(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(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(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(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> mat = ``new` `ArrayList>(` `            ``List.of(``new` `ArrayList(` `                ``List.of(``'.'``, ``'.'``, ``'.'``)` `            ``),` `            ``new` `ArrayList(` `                ``List.of(``'.'``, ``'#'``, ``'.'``)` `            ``),` `            ``new` `ArrayList(` `                ``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)

My Personal Notes arrow_drop_up