Unique paths covering every non-obstacle block exactly once in a grid
Given a grid grid[][] with 4 types of blocks:
- 1 represents the starting block. There is exactly one starting block.
- 2 represents the ending block. There is exactly one ending block.
- 0 represents an empty block we can walk over.
- -1 represents obstacles that we cannot walk over.
The task is to count the number of paths from the starting block to the ending block such that every non-obstacle block is covered exactly once.
Examples:
Input: grid[][] = {
{1, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 2, -1} }
Output: 2
Following are the only paths covering all the non-obstacle blocks:
Input: grid[][] = {
{1, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 2} }
Output: 4
Approach: We can use simple DFS here with backtracking. We can check that a particular path has covered all the non-obstacle blocks by counting all the blocks encountered in the way and finally comparing it with the total number of blocks available and if they match, then we add it as a valid solution.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function for dfs. // i, j ==> Current cell indexes // vis ==> To mark visited cells // ans ==> Result // z ==> Current count 0s visited // z_count ==> Total 0s present void dfs( int i, int j, vector<vector< int > >& grid, vector<vector< bool > >& vis, int & ans, int z, int z_count) { int n = grid.size(), m = grid[0].size(); // Mark the block as visited vis[i][j] = 1; if (grid[i][j] == 0) // update the count z++; // If end block reached if (grid[i][j] == 2) { // If path covered all the non- // obstacle blocks if (z == z_count) ans++; vis[i][j] = 0; return ; } // Up if (i >= 1 && !vis[i - 1][j] && grid[i - 1][j] != -1) dfs(i - 1, j, grid, vis, ans, z, z_count); // Down if (i < n - 1 && !vis[i + 1][j] && grid[i + 1][j] != -1) dfs(i + 1, j, grid, vis, ans, z, z_count); // Left if (j >= 1 && !vis[i][j - 1] && grid[i][j - 1] != -1) dfs(i, j - 1, grid, vis, ans, z, z_count); // Right if (j < m - 1 && !vis[i][j + 1] && grid[i][j + 1] != -1) dfs(i, j + 1, grid, vis, ans, z, z_count); // Unmark the block (unvisited) vis[i][j] = 0; } // Function to return the count of the unique paths int uniquePaths(vector<vector< int > >& grid) { int z_count = 0; // Total 0s present int n = grid.size(), m = grid[0].size(); int ans = 0; vector<vector< bool > > vis(n, vector< bool >(m, 0)); int x, y; for ( int i = 0; i < n; ++i) { for ( int j = 0; j < m; ++j) { // Count non-obstacle blocks if (grid[i][j] == 0) z_count++; else if (grid[i][j] == 1) { // Starting position x = i, y = j; } } } dfs(x, y, grid, vis, ans, 0, z_count); return ans; } // Driver code int main() { vector<vector< int > > grid{ { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 2, -1 } }; cout << uniquePaths(grid); return 0; } |
Java
// Java implementation of the approach import java.util.Arrays; class GFG { static int ans = 0 ; // Function for dfs. // i, j ==> Current cell indexes // vis ==> To mark visited cells // ans ==> Result // z ==> Current count 0s visited // z_count ==> Total 0s present static void dfs( int i, int j, int [][] grid, boolean [][] vis, int z, int z_count) { int n = grid.length, m = grid[ 0 ].length; // Mark the block as visited vis[i][j] = true ; if (grid[i][j] == 0 ) // update the count z++; // If end block reached if (grid[i][j] == 2 ) { // If path covered all the non- // obstacle blocks if (z == z_count) ans++; vis[i][j] = false ; return ; } // Up if (i >= 1 && !vis[i - 1 ][j] && grid[i - 1 ][j] != - 1 ) dfs(i - 1 , j, grid, vis, z, z_count); // Down if (i < n - 1 && !vis[i + 1 ][j] && grid[i + 1 ][j] != - 1 ) dfs(i + 1 , j, grid, vis, z, z_count); // Left if (j >= 1 && !vis[i][j - 1 ] && grid[i][j - 1 ] != - 1 ) dfs(i, j - 1 , grid, vis, z, z_count); // Right if (j < m - 1 && !vis[i][j + 1 ] && grid[i][j + 1 ] != - 1 ) dfs(i, j + 1 , grid, vis, z, z_count); // Unmark the block (unvisited) vis[i][j] = false ; } // Function to return the count of the unique paths static int uniquePaths( int [][] grid) { int z_count = 0 ; // Total 0s present int n = grid.length, m = grid[ 0 ].length; boolean [][] vis = new boolean [n][m]; for ( int i = 0 ; i < n; i++) { Arrays.fill(vis[i], false ); } int x = 0 , y = 0 ; for ( int i = 0 ; i < n; ++i) { for ( int j = 0 ; j < m; ++j) { // Count non-obstacle blocks if (grid[i][j] == 0 ) z_count++; else if (grid[i][j] == 1 ) { // Starting position x = i; y = j; } } } dfs(x, y, grid, vis, 0 , z_count); return ans; } // Driver code public static void main(String[] args) { int [][] grid = { { 1 , 0 , 0 , 0 }, { 0 , 0 , 0 , 0 }, { 0 , 0 , 2 , - 1 } }; System.out.println(uniquePaths(grid)); } } // This code is contributed by sanjeev2552 |
Python3
# Python3 implementation of the approach # Function for dfs. # i, j ==> Current cell indexes # vis ==> To mark visited cells # ans ==> Result # z ==> Current count 0s visited # z_count ==> Total 0s present def dfs(i, j, grid, vis, ans, z, z_count): n = len (grid) m = len (grid[ 0 ]) # Mark the block as visited vis[i][j] = 1 if (grid[i][j] = = 0 ): # Update the count z + = 1 # If end block reached if (grid[i][j] = = 2 ): # If path covered all the non- # obstacle blocks if (z = = z_count): ans + = 1 vis[i][j] = 0 return grid, vis, ans # Up if (i > = 1 and not vis[i - 1 ][j] and grid[i - 1 ][j] ! = - 1 ): grid, vis, ans = dfs(i - 1 , j, grid, vis, ans, z, z_count) # Down if (i < n - 1 and not vis[i + 1 ][j] and grid[i + 1 ][j] ! = - 1 ): grid, vis, ans = dfs(i + 1 , j, grid, vis, ans, z, z_count) # Left if (j > = 1 and not vis[i][j - 1 ] and grid[i][j - 1 ] ! = - 1 ): grid, vis, ans = dfs(i, j - 1 , grid, vis, ans, z, z_count) # Right if (j < m - 1 and not vis[i][j + 1 ] and grid[i][j + 1 ] ! = - 1 ): grid, vis, ans = dfs(i, j + 1 , grid, vis, ans, z, z_count) # Unmark the block (unvisited) vis[i][j] = 0 return grid, vis, ans # Function to return the count # of the unique paths def uniquePaths(grid): # Total 0s present z_count = 0 n = len (grid) m = len (grid[ 0 ]) ans = 0 vis = [[ 0 for j in range (m)] for i in range (n)] x = 0 y = 0 for i in range (n): for j in range (m): # Count non-obstacle blocks if grid[i][j] = = 0 : z_count + = 1 elif (grid[i][j] = = 1 ): # Starting position x = i y = j grid, vis, ans = dfs(x, y, grid, vis, ans, 0 , z_count) return ans # Driver code if __name__ = = '__main__' : grid = [ [ 1 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 ], [ 0 , 0 , 2 , - 1 ] ] print (uniquePaths(grid)) # This code is contributed by rutvik_56 |
C#
// C# implementation of the approach using System; class GFG { static int ans = 0; // Function for dfs. // i, j ==> Current cell indexes // vis ==> To mark visited cells // ans ==> Result // z ==> Current count 0s visited // z_count ==> Total 0s present static void dfs( int i, int j, int [,] grid, bool [,] vis, int z, int z_count) { int n = grid.GetLength(0), m = grid.GetLength(1); // Mark the block as visited vis[i,j] = true ; if (grid[i,j] == 0) // update the count z++; // If end block reached if (grid[i,j] == 2) { // If path covered all the non- // obstacle blocks if (z == z_count) ans++; vis[i,j] = false ; return ; } // Up if (i >= 1 && !vis[i - 1,j] && grid[i - 1,j] != -1) dfs(i - 1, j, grid, vis, z, z_count); // Down if (i < n - 1 && !vis[i + 1,j] && grid[i + 1,j] != -1) dfs(i + 1, j, grid, vis, z, z_count); // Left if (j >= 1 && !vis[i,j - 1] && grid[i,j - 1] != -1) dfs(i, j - 1, grid, vis, z, z_count); // Right if (j < m - 1 && !vis[i,j + 1] && grid[i,j + 1] != -1) dfs(i, j + 1, grid, vis, z, z_count); // Unmark the block (unvisited) vis[i,j] = false ; } // Function to return the count of the unique paths static int uniquePaths( int [,] grid) { int z_count = 0; // Total 0s present int n = grid.GetLength(0), m = grid.GetLength(1); bool [,] vis = new bool [n,m]; for ( int i = 0; i < n; i++) { for ( int j = 0; j < m; j++) { vis[i,j] = false ; } } int x = 0, y = 0; for ( int i = 0; i < n; ++i) { for ( int j = 0; j < m; ++j) { // Count non-obstacle blocks if (grid[i,j] == 0) z_count++; else if (grid[i,j] == 1) { // Starting position x = i; y = j; } } } dfs(x, y, grid, vis, 0, z_count); return ans; } // Driver code static void Main() { int [,] grid = { { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 2, -1 } }; Console.WriteLine(uniquePaths(grid)); } } // This code is contributed by divyesh072019. |
Javascript
<script> // Javascript implementation of the approach let ans = 0; // Function for dfs. // i, j ==> Current cell indexes // vis ==> To mark visited cells // ans ==> Result // z ==> Current count 0s visited // z_count ==> Total 0s present function dfs(i, j, grid, vis, z, z_count) { let n = grid.length, m = grid[0].length; // Mark the block as visited vis[i][j] = true ; if (grid[i][j] == 0) // update the count z++; // If end block reached if (grid[i][j] == 2) { // If path covered all the non- // obstacle blocks if (z == z_count) ans++; vis[i][j] = false ; return ; } // Up if (i >= 1 && !vis[i - 1][j] && grid[i - 1][j] != -1) dfs(i - 1, j, grid, vis, z, z_count); // Down if (i < n - 1 && !vis[i + 1][j] && grid[i + 1][j] != -1) dfs(i + 1, j, grid, vis, z, z_count); // Left if (j >= 1 && !vis[i][j - 1] && grid[i][j - 1] != -1) dfs(i, j - 1, grid, vis, z, z_count); // Right if (j < m - 1 && !vis[i][j + 1] && grid[i][j + 1] != -1) dfs(i, j + 1, grid, vis, z, z_count); // Unmark the block (unvisited) vis[i][j] = false ; } // Function to return the count of the unique paths function uniquePaths(grid) { let z_count = 0; // Total 0s present let n = grid.length, m = grid[0].length; let vis = new Array(n); for (let i = 0; i < n; i++) { vis[i] = new Array(m); for (let j = 0; j < m; j++) { vis[i][j] = false ; } } let x = 0, y = 0; for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { // Count non-obstacle blocks if (grid[i][j] == 0) z_count++; else if (grid[i][j] == 1) { // Starting position x = i; y = j; } } } dfs(x, y, grid, vis, 0, z_count); return ans; } let grid = [ [ 1, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 2, -1 ] ]; document.write(uniquePaths(grid)); // This code is contributed by decode2207. </script> |
2
Time Complexity: O(row * cols)
Auxiliary Space: O(row * cols)
The Recursive DFS.
C++
#include<bits/stdc++.h> #include<iostream> #define ll long long //ll mod=1e9+7; using namespace std; int res = 0, empty = 1; void path(vector<vector< int >>& grid, int x, int y, int count) { if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == -1) return ; if (grid[x][y] == 2) { if (empty == count) res++; return ; } grid[x][y] = -1; path(grid, x+1, y, count+1); path(grid, x-1, y, count+1); path(grid, x, y+1, count+1); path(grid, x, y-1, count+1); grid[x][y] = 0; } int uniquePathsIII(vector<vector< int >>& grid) { int start_x, start_y; for ( int i = 0; i < grid.size(); i++) { for ( int j = 0; j < grid[0].size(); j++) { if (grid[i][j] == 1) start_x = i, start_y = j; else if (grid[i][j] == 0) empty++; } } path(grid, start_x, start_y, 0); return res; } signed main(){ vector<vector< int >>grid{{1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 2, -1}}; cout<<uniquePathsIII(grid)<<endl; return 0; } |
Python3
# function to count all possible unique paths in the grid # from start to end, considering empty cells and obstacles def uniquePathsIII(grid): res = 0 empty = 1 # recursive function to traverse through the grid def path(x, y, count): nonlocal res # check if current cell is out of grid or is an obstacle if x < 0 or x > = len (grid) or y < 0 or y > = len (grid[ 0 ]) or grid[x][y] = = - 1 : return # check if current cell is the end cell if grid[x][y] = = 2 : if empty = = count: res + = 1 return # mark current cell as visited grid[x][y] = - 1 # recursively call path function for all possible directions path(x + 1 , y, count + 1 ) path(x - 1 , y, count + 1 ) path(x, y + 1 , count + 1 ) path(x, y - 1 , count + 1 ) # mark current cell as unvisited grid[x][y] = 0 # initialize start coordinates and empty cell count for i in range ( len (grid)): for j in range ( len (grid[ 0 ])): if grid[i][j] = = 1 : start_x, start_y = i, j elif grid[i][j] = = 0 : empty + = 1 # call path function starting from the start cell path(start_x, start_y, 0 ) return res # test the function grid = [[ 1 , 0 , 0 , 0 ], [ 0 , 0 , 0 , 0 ], [ 0 , 0 , 2 , - 1 ]] print (uniquePathsIII(grid)) # This code is contributed by lokeshpotta20. |
C#
using System; public class Gfg { static int res = 0, empty = 1; static void path( int [ , ] grid, int x, int y, int count) { if (x < 0 || x >= grid.GetLength(0) || y < 0 || y >= grid.GetLength(1) || grid[x, y] == -1) return ; if (grid[x, y] == 2) { if (empty == count) res++; return ; } grid[x, y] = -1; path(grid, x+1, y, count+1); path(grid, x-1, y, count+1); path(grid, x, y+1, count+1); path(grid, x, y-1, count+1); grid[x, y] = 0; } static int uniquePathsIII( int [, ] grid) { int start_x=-1, start_y=-1; for ( int i = 0; i < grid.GetLength(0); i++) { for ( int j = 0; j < grid.GetLength(1); j++) { if (grid[i, j] == 1) { start_x = i; start_y = j; } else if (grid[i, j] == 0) empty++; } } path(grid, start_x, start_y, 0); return res; } public static void Main( string [] args) { int [ , ] grid={{1, 0, 0, 0},{0, 0, 0, 0},{0, 0, 2, -1}}; Console.WriteLine(uniquePathsIII(grid)); } } // This code is contributed by ritaagarwal. |
Javascript
let mod=1e9+7; let res = 0, empty = 1; function path(grid, x, y, count) { if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == -1) return ; if (grid[x][y] == 2) { if (empty == count) res++; return ; } grid[x][y] = -1; path(grid, x+1, y, count+1); path(grid, x-1, y, count+1); path(grid, x, y+1, count+1); path(grid, x, y-1, count+1); grid[x][y] = 0; } function uniquePathsIII(grid) { let start_x, start_y; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) start_x = i, start_y = j; else if (grid[i][j] == 0) empty++; } } path(grid, start_x, start_y, 0); return res; } let grid= [[1, 0, 0, 0],[0, 0, 0, 0],[0, 0, 2, -1]]; console.log(uniquePathsIII(grid)); // This code is contributed by poojaagarwal2. |
Java
// Java code for the above approach import java.io.*; class GFG { static int res = 0 , empty = 1 ; static void path( int [][] grid, int x, int y, int count) { if (x < 0 || x >= grid.length || y < 0 || y >= grid[ 0 ].length || grid[x][y] == - 1 ) return ; if (grid[x][y] == 2 ) { if (empty == count) res++; return ; } grid[x][y] = - 1 ; path(grid, x + 1 , y, count + 1 ); path(grid, x - 1 , y, count + 1 ); path(grid, x, y + 1 , count + 1 ); path(grid, x, y - 1 , count + 1 ); grid[x][y] = 0 ; } static int uniquePathsIII( int [][] grid) { int start_x = - 1 , start_y = - 1 ; for ( int i = 0 ; i < grid.length; i++) { for ( int j = 0 ; j < grid[ 0 ].length; j++) { if (grid[i][j] == 1 ) { start_x = i; start_y = j; } else if (grid[i][j] == 0 ) empty++; } } path(grid, start_x, start_y, 0 ); return res; } public static void main(String[] args) { int [][] grid = { { 1 , 0 , 0 , 0 }, { 0 , 0 , 0 , 0 }, { 0 , 0 , 2 , - 1 } }; System.out.println(uniquePathsIII(grid)); } } // This code is contributed by lokeshmvs21. |
2
Since we are exploring all possible paths by making grid[x][y]=0 at end of the call, so complexity will be exponential.
Time Complexity: O((row * cols)!)
Auxiliary Space: O(row * cols)
Please Login to comment...