Day-9 Leetcode Coding Journey: Mastering Problem-Solving Techniques
LeetCode #63: Unique Paths II
Problem Statement
You are given an m x n
grid where some cells contain obstacles (1
) and others are free (0
).
The robot starts at the top-left corner and can only move right or down.
The robot must reach the bottom-right corner of the grid.
Find the number of unique paths the robot can take while avoiding obstacles.
Constraints
1≤m,n≤100
obstacleGrid[i][j]
is either0
(free cell) or1
(obstacle).
🚀 Code Implementation
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m, n = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1:
return 0
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i in range(1, m):
if obstacleGrid[i][0] == 0:
dp[i][0] = dp[i-1][0]
for j in range(1, n):
if obstacleGrid[0][j] == 0:
dp[0][j] = dp[0][j-1]
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 dp[m-1][n-1]
LeetCode #64: Minimum Path Sum
Problem Statement
Given an m x n
grid filled with non-negative numbers, find a path from the top-left to the bottom-right corner that minimizes the sum of all numbers along the path.
You can only move right or down at any point in time.
Constraints
1≤m,n≤100
0≤grid[i][j]≤100
🚀 Code Implementation
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m, n = len(grid), len(grid[0])
for j in range(1, n):
grid[0][j] += grid[0][j - 1]
for i in range(1, m):
grid[i][0] += grid[i - 1][0]
for i in range(1, m):
for j in range(1, n):
grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])
return grid[m - 1][n - 1]