Similar Problems

Similar Problems not available

Maximum Enemy Forts That Can Be Captured - Leetcode Solution

Companies:

LeetCode:  Maximum Enemy Forts That Can Be Captured Leetcode Solution

Difficulty: Easy

Topics: array two-pointers  

Problem Statement:

You are given a grid of size n x m representing a battlefield, and each cell of the grid represents an enemy fortress. You have a team of soldiers who can capture these enemy fortresses. However, the soldiers can only move in two directions - right and down.

You have to find the maximum number of enemy fortresses that your team can capture. Your team starts at the top-left corner of the grid, and they have to move towards the bottom-right cell of the grid. When your team reaches a cell containing an enemy fortress, they capture it, and the fortress becomes inaccessible.

Approach:

This problem can be easily solved using dynamic programming. We will define a two-dimensional array dp[n][m], where dp[i][j] represents the maximum number of enemy fortresses that can be captured if we start from the cell (i, j).

To fill the dp array, we will start from the bottom-right cell (n-1, m-1). We will initialize dp[n-1][m-1] to 1 if the cell contains an enemy fortress, and 0 otherwise. Then, we will fill the last row (i.e., cells with row index n-1), and the last column (i.e., cells with column index m-1) of the dp array using the following recurrence relation:

dp[n-1][j] = dp[n-1][j+1] + (1 if there is an enemy fortress in cell (n-1, j), 0 otherwise) dp[i][m-1] = dp[i+1][m-1] + (1 if there is an enemy fortress in cell (i, m-1), 0 otherwise)

Once we have filled the last row and last column of the dp array, we can fill the remaining cells of the dp array using the following recurrence relation:

dp[i][j] = max(dp[i+1][j], dp[i][j+1]) + (1 if there is an enemy fortress in cell (i, j), 0 otherwise)

Finally, the maximum number of enemy fortresses that our team can capture is given by dp[0][0].

Time Complexity:

The time complexity of the above approach is O(nm), where n and m are the dimensions of the battlefield.

Space Complexity:

The space complexity of the above approach is also O(nm), due to the use of the dp array.

Code:

Following is the implementation of the above approach in Python:

def maxEnemyForts(grid): n, m = len(grid), len(grid[0]) dp = [[0] * m for _ in range(n)]

# Fill last row and last column
for j in range(m-1, -1, -1):
    dp[n-1][j] = grid[n-1][j] + dp[n-1][j+1] if j < m-1 else grid[n-1][j]
for i in range(n-1, -1, -1):
    dp[i][m-1] = grid[i][m-1] + dp[i+1][m-1] if i < n-1 else grid[i][m-1]

# Fill remaining cells
for i in range(n-2, -1, -1):
    for j in range(m-2, -1, -1):
        dp[i][j] = max(dp[i+1][j], dp[i][j+1]) + grid[i][j]

return dp[0][0]

Example:

Input: grid = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]

Output: 3

Explanation: The team can capture the enemy fortresses at cells (0, 0), (1, 0), and (2, 1).

Maximum Enemy Forts That Can Be Captured Solution Code

1