text: Unique paths covering every non | Function for dfs . i , j == > Current cell indexes vis == > To mark visited cells ans == > Result z == > Current count 0 s visited z_count == > Total 0 s present ; Mark the block as visited ; Update the count ; If end block reached ; If path covered all the non - obstacle blocks ; Up ; Down ; Left ; Right ; Unmark the block ( unvisited ) ; Function to return the count of the unique paths ; Total 0 s present ; Count non - obstacle blocks ; Starting position ; Driver code
code: def dfs ( i , j , grid , vis , ans , z , z_count ) : NEW_LINE INDENT n = len ( grid ) NEW_LINE m = len ( grid [ 0 ] ) NEW_LINE vis [ i ] [ j ] = 1 NEW_LINE if ( grid [ i ] [ j ] == 0 ) : NEW_LINE INDENT z += 1 NEW_LINE DEDENT if ( grid [ i ] [ j ] == 2 ) : NEW_LINE INDENT if ( z == z_count ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT vis [ i ] [ j ] = 0 NEW_LINE return grid , vis , ans NEW_LINE DEDENT if ( i >= 1 and not vis [ i - 1 ] [ j ] and grid [ i - 1 ] [ j ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i - 1 , j , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( i < n - 1 and not vis [ i + 1 ] [ j ] and grid [ i + 1 ] [ j ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i + 1 , j , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( j >= 1 and not vis [ i ] [ j - 1 ] and grid [ i ] [ j - 1 ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i , j - 1 , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( j < m - 1 and not vis [ i ] [ j + 1 ] and grid [ i ] [ j + 1 ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i , j + 1 , grid , vis , ans , z , z_count ) NEW_LINE DEDENT vis [ i ] [ j ] = 0 NEW_LINE return grid , vis , ans NEW_LINE DEDENT def uniquePaths ( grid ) : NEW_LINE INDENT z_count = 0 NEW_LINE n = len ( grid ) NEW_LINE m = len ( grid [ 0 ] ) NEW_LINE ans = 0 NEW_LINE vis = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if grid [ i ] [ j ] == 0 : NEW_LINE INDENT z_count += 1 NEW_LINE DEDENT elif ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT x = i NEW_LINE y = j NEW_LINE DEDENT DEDENT DEDENT grid , vis , ans = dfs ( x , y , grid , vis , ans , 0 , z_count ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 2 , - 1 ] ] NEW_LINE print ( uniquePaths ( grid ) ) NEW_LINE DEDENT