Similar Problems

Similar Problems not available

Walking Robot Simulation Ii - Leetcode Solution

Companies:

LeetCode:  Walking Robot Simulation Ii Leetcode Solution

Difficulty: Medium

Topics: design simulation  

The Walking Robot Simulation II problem on LeetCode is a simulation problem that involves simulating the movements of a robot on a grid.

Problem Statement: A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be?

Example: Input: m = 3, n = 2 obstacles = [[1,0]] Output: 1 Explanation: There is only one path to the target. Input: m = 7, n = 3 obstacles = [[0,1],[1,0],[3,3],[4,3],[5,2],[5,4]] Output: 0 Explanation: There is no path to the target.

Solution Approach: The problem can be solved using Dynamic Programming. We can create a 2D table to store the number of paths for each cell in the grid. The number of paths for the current cell can be calculated by adding the number of paths for the cell to its left and the cell above it. If the cell has an obstacle, then the number of paths for that cell is 0.

We can use a recursive approach to fill the table. The base case would be when the robot is at the top-left corner, and the number of paths for that cell is 1. We can then fill out the table row by row, from left to right. For each cell, we can calculate the number of paths by adding the number of paths for the cell to its left and the cell above it. If the cell has an obstacle, then the number of paths for that cell is 0.

The final answer would be the number of paths for the bottom-right corner.

Code in Python:

def uniquePathsWithObstacles(obstacleGrid):
    m = len(obstacleGrid)
    n = len(obstacleGrid[0])

    # Table to store number of paths for each cell in the grid
    dp = [[0 for x in range(n)] for y in range(m)]
    
    # Base case - robot is at the top-left corner
    if obstacleGrid[0][0] == 0:
        dp[0][0] = 1
    
    # Fill the first row of the table
    for i in range(1, n):
        if obstacleGrid[0][i] == 0:
            dp[0][i] = dp[0][i-1]
    
    # Fill the first column of the table
    for i in range(1, m):
        if obstacleGrid[i][0] == 0:
            dp[i][0] = dp[i-1][0]
    
    # Fill the rest of the table
    for i in range(1, m):
        for j in range(1, n):
            if obstacleGrid[i][j] == 0:
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
    
    # Return the number of paths for the bottom-right corner
    return dp[m-1][n-1]

Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the grid. Space Complexity: O(m * n), to store the 2D table.

Walking Robot Simulation Ii Solution Code

1