What Is Grid DP and Why Is It Important?

Grid DP (dynamic programming on a grid) is a special class of problems in which we work with a two-dimensional matrix (grid) and want to calculate a value for each cell based on previously calculated cells.

The most common example is the following:

  • We are given a matrix of dimensions n × m,
  • we start in the top-left corner,
  • we want to reach the bottom-right corner,
  • we are allowed to move only right or down.

The question is: In how many different ways can we reach the destination?

At first glance, the problem may seem combinatorial, but the number of possible paths quickly becomes enormous. Generating every possible path would be too slow, because the number of combinations grows exponentially.

This is where dynamic programming comes in. Instead of repeating the same calculations, we use the fact that each cell can be reached from a previously visited cell, allowing us to build the result step by step.


Why Is Grid DP Important in Competitions?

Grid DP problems are extremely common in competitive programming and in technical screening tests for IT companies.

  • Counting paths through a grid
  • Minimum path sum
  • Maximum value of collected points
  • Problems involving obstacles
  • Movement in multiple directions

Understanding this type of problem makes it easier to learn more advanced DP techniques, because it introduces the use of two-dimensional states.

If you have already studied 1D dynamic programming (such as the Fibonacci sequence), Grid DP is a natural next step: instead of one dimension, we now work with two.


This problem often appears in tasks involving movement through a matrix, using related techniques such as BFS (Breadth-First Search) when minimizing the number of steps. For such problems, see the Grid BFS section in the graph algorithms lesson.

For problems involving movement through an unweighted grid (for example, finding the minimum number of steps), also see Grid BFS, which uses graph traversal on a matrix.

Description of the Basic Problem

Consider a rectangular matrix with dimensions n × m. The cells are indexed from (0, 0) to (n−1, m−1).

We start at cell (0, 0) — the top-left corner — and our goal is to reach cell (n−1, m−1) — the bottom-right corner.

Only the following moves are allowed:

  • one step to the right (i, j → i, j+1)
  • one step down (i, j → i+1, j)

We need to determine how many different ways we can reach the destination cell from the starting cell.


Why Is the Naive Solution Too Slow?

One possible approach would be to recursively generate every possible path. However, the number of paths quickly increases as the matrix dimensions grow.

For example, even for a 20 × 20 matrix, the number of paths is very large, so generating every combination would be extremely slow.

This is why we use dynamic programming: instead of repeating the same calculations, we store the results for every cell.


Defining the DP State

We define a two-dimensional array:

  • dp[i][j] represents the number of different paths by which we can reach cell (i, j).

This means that, for every cell, we want to know how many different ways there are to reach it using the permitted moves.

Our final goal is to calculate:

  • dp[n-1][m-1]

which represents the total number of different paths to the destination.


DP Transition (Recurrence Relation)

To calculate the value of dp[i][j], we ask: From which cells can we reach cell (i, j)?

Since only two moves are allowed — right and down — we can reach cell (i, j):

  • from the cell above: (i-1, j)
  • from the cell to the left: (i, j-1)

If we know the number of paths to those cells, the total number of paths to cell (i, j) is equal to the sum of those two numbers.

Therefore, we obtain the basic DP recurrence:

  • dp[i][j] = dp[i-1][j] + dp[i][j-1]

Base Cases

For the recurrence to work correctly, we must define the initial values.

  • dp[0][0] = 1
    — there is exactly one way to be at the starting cell.

For the first row (i = 0):

  • We can move only to the right, so every element is equal to 1.

For the first column (j = 0):

  • We can move only down, so every element is also equal to 1.

We have now defined all the conditions needed to fill the entire DP table.


How the DP Table Is Filled

Each cell represents the number of ways to reach that position. For an inner cell, we add the values from the cell above and the cell to the left: dp[i][j] = dp[i-1][j] + dp[i][j-1].

Value from above Value from the left

The bottom-right cell contains 6. Use the controls to see how the table is filled step by step.

The first row and first column contain 1 because there is only one way to reach each of those cells. The remaining values are calculated using the DP recurrence.

C++ Implementation (With Explanations)


#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    // n = number of rows
    // m = number of columns

    // Create an n x m DP table
    // dp[i][j] = number of ways to reach cell (i, j)
    vector<vector<int>> dp(n, vector<int>(m, 0));

    // Starting cell
    dp[0][0] = 1;

    // Fill the DP table
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {

            // If we can reach this cell from above
            if (i > 0)
                dp[i][j] += dp[i-1][j];

            // If we can reach this cell from the left
            if (j > 0)
                dp[i][j] += dp[i][j-1];
        }
    }

    // Final answer
    cout << dp[n-1][m-1];
}

Grid with Obstacles

In many problems, some cells cannot be used because they contain obstacles. In that case:

  • If a cell is an obstacle → dp[i][j] = 0
  • Otherwise, we use the same recurrence as before.

Grid DP with an Obstacle

The red cell is blocked, so its DP value is 0. We cannot pass through it. The algorithm counts the remaining paths that go around the obstacle.

Value from above Value from the left Obstacle: DP = 0

The center cell is blocked. Its value is 0, and the final DP value is 2, meaning there are two valid paths.

A blocked cell contributes no paths. The cells around it are calculated normally, using the values above and to the left. In this example, the bottom-right cell has value 2.

Before calculating a cell's value, we check whether the cell is allowed. If the starting cell is blocked, the result is 0.


#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<int>> grid(n, vector<int>(m));
    vector<vector<long long>> dp(n, vector<long long>(m, 0));

    // Read the matrix
    // 0 = free cell
    // 1 = obstacle
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> grid[i][j];

    if (grid[0][0] == 0)
        dp[0][0] = 1;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {

            if (grid[i][j] == 1) {
                dp[i][j] = 0; // obstacle
                continue;
            }

            if (i > 0)
                dp[i][j] += dp[i-1][j];

            if (j > 0)
                dp[i][j] += dp[i][j-1];
        }
    }

    cout << dp[n-1][m-1];
}

Algorithm Complexity

  • Time complexity: O(n × m)
  • Space complexity: O(n × m)

Since every cell is calculated exactly once, the algorithm is very efficient and suitable for medium-sized matrices (n and m up to a few thousand).


Memory Optimization

Since we need only the current and previous row for the calculation, we can reduce memory usage from O(n × m) to O(m).

This is a common technique in competitions when the constraints are large.


Example of Filling the DP Table

Consider a simple matrix with dimensions 3 × 3. We want to calculate the number of paths from (0,0) to (2,2).

Initially, we set:

  • dp[0][0] = 1
  • First row = 1 (movement only to the right)
  • First column = 1 (movement only down)

1 1 1
1 ? ?
1 ? ?

We now calculate the remaining cells using the recurrence:

dp[i][j] = dp[i-1][j] + dp[i][j-1]


Cell (1,1):

  • We arrive from (0,1) = 1
  • We arrive from (1,0) = 1

Therefore:

dp[1][1] = 1 + 1 = 2


1 1 1
1 2 ?
1 ? ?

Cell (1,2):

  • We arrive from (0,2) = 1
  • We arrive from (1,1) = 2

dp[1][2] = 1 + 2 = 3


Cell (2,1):

  • We arrive from (1,1) = 2
  • We arrive from (2,0) = 1

dp[2][1] = 2 + 1 = 3


Finally, cell (2,2):

  • We arrive from (1,2) = 3
  • We arrive from (2,1) = 3

dp[2][2] = 3 + 3 = 6


1 1 1
1 2 3
1 3 6

Therefore, there are 6 different paths from the top-left to the bottom-right corner of a 3 × 3 grid.

This example clearly shows how the table is built incrementally: each cell depends only on neighbors that have already been calculated.


Grid with Obstacles

Some cells may be unusable because they contain obstacles. We can mark obstacles with 1, while free cells are marked with 0.

If a cell contains an obstacle:


dp[i][j] = 0

Example: Grid with Obstacles (C++)


#include <iostream>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    int grid[n][m];
    long long dp[n][m];

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            cin >> grid[i][j];

    if(grid[0][0] == 1) {
        cout << 0;
        return 0;
    }

    dp[0][0] = 1;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(grid[i][j] == 1) {
                dp[i][j] = 0;
            } else {
                if(i == 0 && j == 0) continue;
                long long fromUp = (i > 0) ? dp[i-1][j] : 0;
                long long fromLeft = (j > 0) ? dp[i][j-1] : 0;
                dp[i][j] = fromUp + fromLeft;
            }
        }
    }

    cout << dp[n-1][m-1];
    return 0;
}

Algorithm Complexity

Let us analyze the efficiency of our solution.


Time Complexity

We fill the DP table of dimensions n × m by calculating each cell exactly once.

For every cell, we perform a constant number of operations (adding two values).

Therefore, the total time complexity is:

  • O(n × m)

This is a very efficient solution, because every state is calculated only once.


Space Complexity

We use a two-dimensional table of size n × m, so the space complexity is:

  • O(n × m)

This is perfectly acceptable for medium-sized matrices (n and m up to a few thousand).


When Can Problems Occur?

  • If the dimensions are extremely large (for example, 105 × 105), memory becomes an issue.
  • If the number of paths is very large, the range of the int type may be exceeded.

In such situations, we use:

  • the long long variable type
  • calculating results modulo a number (for example, 109 + 7)
  • memory optimization to O(m)

This makes Grid DP applicable to much larger inputs.


Variant: Minimum Path Sum

In this version of the problem, each cell in the matrix contains a value (a cost).

The goal is no longer to count paths, but to find the minimum possible sum of the values of the cells we pass through from (0,0) to (n−1,m−1).

The permitted moves are still:

  • right
  • down

Defining the DP State

  • dp[i][j] represents the minimum sum needed to reach cell (i, j).

DP Recurrence

Since we can reach cell (i, j) from the cell above or from the left, we choose the path with the smaller sum:

  • dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]

Base Cases

  • dp[0][0] = grid[0][0]
  • The first row is filled by adding values from the left.
  • The first column is filled by adding values from above.

C++ Implementation


#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<int>> grid(n, vector<int>(m));
    vector<vector<int>> dp(n, vector<int>(m));

    // Read the matrix
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> grid[i][j];

    dp[0][0] = grid[0][0];

    // Fill the first row
    for (int j = 1; j < m; j++)
        dp[0][j] = dp[0][j-1] + grid[0][j];

    // Fill the first column
    for (int i = 1; i < n; i++)
        dp[i][0] = dp[i-1][0] + grid[i][0];

    // Fill the rest of the table
    for (int i = 1; i < n; i++) {
        for (int j = 1; j < m; j++) {
            dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
        }
    }

    cout << dp[n-1][m-1];
}

Here we can see that the structure of the problem does not change; only the operation changes:

  • for counting → addition
  • for optimization → minimum (or maximum)

This shows how flexible and powerful Grid DP is.


Variant: Maximum Path Sum

In this version, each cell in the matrix contains a value. The goal is to find the path with the maximum sum of values from (0,0) to (n−1,m−1), moving only right or down.

This variant is similar to the Minimum Path Sum problem, except that we choose the maximum instead of the minimum.


Defining the DP State

  • dp[i][j] represents the maximum sum we can collect by reaching cell (i,j).

DP Recurrence

For every cell (i,j), we can arrive from above or from the left:

  • dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j]

Base cases:

  • dp[0][0] = grid[0][0]
  • The first row is filled by adding values from the left.
  • The first column is filled by adding values from above.

C++ Implementation


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    vector<vector<int>> grid(n, vector<int>(m));
    vector<vector<int>> dp(n, vector<int>(m));

    // Read the matrix
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> grid[i][j];

    dp[0][0] = grid[0][0];

    // Fill the first row
    for (int j = 1; j < m; j++)
        dp[0][j] = dp[0][j-1] + grid[0][j];

    // Fill the first column
    for (int i = 1; i < n; i++)
        dp[i][0] = dp[i-1][0] + grid[i][0];

    // Fill the rest of the table
    for (int i = 1; i < n; i++) {
        for (int j = 1; j < m; j++) {
            dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + grid[i][j];
        }
    }

    cout << dp[n-1][m-1];
}

This variant shows that the same DP table structure can solve different tasks simply by changing the operation (addition → minimum/maximum, or counting).


Competition Notes and Edge Cases

When solving Grid DP problems in competitions or practice, it is important to pay attention to a few practical details.


1. Variable Type

  • The number of paths can become very large very quickly.
  • Use long long instead of int when the value exceeds approximately 109.
  • If the problem requires modulo arithmetic (for example, 109 + 7), apply the modulo after each addition.

2. The Starting Cell May Be Blocked

  • If dp[0][0] is an obstacle, the result is immediately 0.
  • The same applies if the destination is blocked — there is no solution.

3. Matrix Dimensions

  • For very large matrices (n, m > 104), a two-dimensional table may use too much memory.
  • In such cases, use memory optimization: store only the previous row (O(m) space).

4. Edge Cases

  • One row or one column — DP reduces to simple addition.
  • Negative values in the matrix — minimum or maximum path sums may require careful initialization.
  • Obstacles along the edges of the matrix — check the DP recurrence to avoid out-of-bounds access.

5. Advice for Competitors

  • First solve the basic problem without obstacles to understand how the table is filled.
  • Then add obstacles and sum optimization.
  • Always test small examples manually to verify the logic.

Advanced Variant: Minimum Total Movement in a Grid

In this advanced version of Grid DP, each cell of an n × m matrix contains a number of people. Dorm Lander must choose a path from the top-left cell (0,0) to the bottom-right cell (n-1,m-1), moving only:

  • Right →
  • Down ↓

The goal is not to minimize the sum of the values along the path. Instead, we must minimize the total distance traveled by all people as they move to the nearest cell on the chosen path.

The challenge is to choose the path that minimizes the combined movement cost of everyone in the grid.


Why Is Standard Grid DP Not Enough?

In a classic minimum-path-sum problem, we often use the recurrence:


dp[i][j] =
    min(dp[i-1][j], dp[i][j-1]) + grid[i][j];

We cannot apply this recurrence directly to the current problem because the additional cost of extending the path is not simply the value stored in the current cell.

Instead, the additional cost depends on:

  • the number of people in relevant cells;
  • their distances from the newly extended path;
  • whether the path arrives from above or from the left.

We therefore need to model the cost of extending the path, rather than treating each cell's value as its movement cost.


The Key Idea

Instead of considering the problem only from the perspective of each individual person, imagine building the path one cell at a time.

Whenever the path reaches a new cell:

  • a new part of a row or column becomes part of the path;
  • some people can reach the path for the first time;
  • their additional movement cost is calculated.

The DP algorithm compares the possible ways to extend the path and keeps the minimum accumulated cost for each state.


How Does the Path Expand?

Suppose the path reaches cell (i,j). There are two possible directions from which it can arrive:

  • From above: the path enters the current row at column j.
  • From the left: the path enters the current column at row i.

The important observation is that we do not need to recalculate the contribution of every cell in the matrix. We calculate only the additional cost associated with extending the path in the chosen direction.


What Does the DP State Represent?

We use the state:


dp[i][j]

It represents the minimum accumulated movement cost among the path prefixes that end at cell (i,j), according to the cost accounting described below.

The transition considers the two possible predecessors:


dp[i][j] = min(
    dp[i-1][j] + costFromAbove,
    dp[i][j-1] + costFromLeft
);

Here, costFromAbove and costFromLeft are the additional movement costs associated with extending the path from the corresponding predecessor. A transition is considered only when that predecessor exists.

Unlike the standard minimum-path-sum problem, these additional costs must be calculated efficiently.


The Naive Approach and Its Limitation

Suppose the path arrives at cell (i,j) from above. Under the path-expansion interpretation, we must calculate the contribution of people in the current row who are to the left of column j.


(i,1), (i,2), ..., (i,j-1)

People in column k must move j-k steps to reach column j. If a[i][k] is the number of people in that cell, the additional cost is:


costFromAbove =
    sum(a[i][k] * (j-k)), for 1 <= k < j;

A straightforward implementation would iterate through every column to the left of j. Repeating this calculation for every cell would be inefficient.


Optimization Using Weighted Prefix Sums

We can evaluate the previous sum in constant time by maintaining two prefix sums for each row:

  • rowSum: the sum of the numbers of people in the preceding cells of the current row;
  • weightedRowSum: the sum of a[i][k] * k over those cells.

We start with:


sum(a[i][k] * (j-k))
=
j * sum(a[i][k]) - sum(a[i][k] * k);

Therefore, the cost can be calculated as:


costFromAbove = j * rowSum - weightedRowSum;

Because both prefix sums are maintained while processing the row, the additional cost can be calculated in O(1) time.

We use the same idea for the cost of arriving from the left. In that case, we maintain prefix sums for each column:

  • columnSum[j]: the sum of the numbers of people in the cells above the current cell;
  • weightedColumnSum[j]: the sum of a[r][j] * r over those cells.

The corresponding cost is:


costFromLeft =
    i * columnSum[j] - weightedColumnSum[j];

What Do the Variables k and r Represent?

The indices k and r identify the cells included in the sums:

  • k is a column index in the current row.
  • r is a row index in the current column.

For example:


sum(a[i][k] * (j-k))

adds the movement costs of people in cells to the left of column j. Each person in column k contributes j-k steps.

Similarly:


sum(a[r][j] * (i-r))

adds the movement costs of people in cells above row i. Each person in row r contributes i-r steps.


Why Is This Approach Efficient?

The movement restrictions are important: both the selected path and the people move only right or down. This allows us to reason about how the path expands through the grid.

Under the cost-accounting scheme used by the DP recurrence, each newly included group contributes its cost at the corresponding transition. The prefix sums let us calculate that contribution without scanning the same row or column repeatedly.

With constant-time cost calculations for each transition, the resulting algorithm can process the grid in O(n × m) time, using the rolling-row DP implementation shown in the solution.


Common Questions

  • Do we need to remember which cells have already been processed?
    No separate visited table is required by this DP formulation. The state and the maintained prefix sums describe the information needed for each transition.
  • Do we scan an entire row or column for every transition?
    No. Weighted prefix sums allow us to calculate the corresponding sum in O(1) time.
  • Can the same contribution be counted more than once?
    The cost accounting must be defined so that each contribution is included exactly as intended by the mathematical model. This is a key part of proving the recurrence correct.
  • Would the same approach work if movement to the left or upward were allowed?
    Not directly. Allowing those moves changes the structure of the path and may invalidate this simple path-expansion recurrence.

Conclusion

This advanced problem illustrates how dynamic programming can be combined with weighted prefix sums and careful mathematical modeling.

The central challenge is to define the additional cost introduced by each transition and to ensure that the recurrence accounts for every movement correctly.

Once the model is established and proved correct, weighted prefix sums can reduce the cost of each transition to O(1), allowing an O(n × m) implementation.


Visual Intuition — How the Path "Expands"

The most important idea in this problem is to avoid viewing the path all at once. Instead, we treat it as a process that gradually expands through the matrix.

When the path reaches a new cell:

  • a new part of a row or column is added
  • only those new cells come into contact with the path for the first time
  • we calculate their contribution to the total cost

Arriving from Above

Suppose we arrive from cell (i-1,j) at cell (i,j).

For example:

  • i = 4
  • j = 3

We therefore arrive at cell:

(4,3)

The path then reaches part of the fourth row for the first time.

X X X X
X X X X
X X X X
? ? (i,j)
(4,3)
.


Legend:
  • X = cells already processed
  • ? = new cells that are included in the calculation for the first time
  • (i,j) = the current cell reached by DP

When we arrive from above:

  • a new part of the row is added
  • specifically, the cells: (i,1), (i,2), ..., (i,j)

In the example above, these are:


(4,1), (4,2), (4,3)

All people in those cells must move right to reach column j.

If someone is located at cell:


(i,k)

they must travel:


j - k

steps.


What Does the Variable k Represent?

The variable k represents:

  • the current column within the current row

A naive approach would be:


for(int k = 1; k < j; k++) {
    sum += a[i][k] * (j - k);
}

In other words:

  • we visit every cell to the left of column j
  • and add its contribution

But this would be too slow.

That is why we use prefix sums and the formula:


∑ a[i][k] * (j-k)
=
j * ∑a[i][k] - ∑(a[i][k] * k)

Arriving from the Left

Now suppose we arrive from:


(i,j-1)

at cell:


(i,j)

For example:

  • i = 4
  • j = 4
X X X ?
X X X ?
X X X ?
X X X (i,j)
(4,4)


Here we add a new column:


(1,j), (2,j), ..., (i,j)

In the example above:


(1,4), (2,4), (3,4), (4,4)

The people must now move down to row i.

If someone is located at:


(r,j)

they must travel:


i - r

steps.


What Does the Variable r Represent?

The variable r represents:

  • the current row within the current column

A naive approach would be:


for(int r = 1; r < i; r++) {
    sum += a[r][j] * (i - r);
}

But this would also be too slow for large matrices.

Therefore, we use:


∑ a[r][j] * (i-r)
=
i * ∑a[r][j] - ∑(a[r][j] * r)

Why Is This Important?

  • we calculate every contribution exactly once ✔
  • we do not traverse the entire matrix at every step ✔
  • DP remains efficient ✔
  • prefix sums allow calculations in O(1) ✔

Interactive Example — Prefix Sums and a K×K Square

The following example shows how prefix sums work in a matrix.

Hover over a table cell to see:

  • the prefix-sum value for that cell
  • the sum of the K×K square ending at that cell, if one exists


What Does Each Cell Represent?

Each cell displays:


prefix[i][j]

that is, the sum of all elements in the region:


(0,0) → (i,j)

For example:


prefix[2][2]

contains the sum of all elements in the region:


X X X
X X X
X X X

How Do We Calculate the Sum of a K×K Square?

When we want the sum of a region:

  • we do not iterate over every cell in the square ❌
  • we use previously calculated prefix values instead ✔

Formula:


sum =
prefix[i][j]
- prefix[i-K][j]
- prefix[i][j-K]
+ prefix[i-K][j-K]

This allows us to:

  • calculate each sum in O(1)
  • without additional loops

What Should You Notice?

  • Prefix sums store information about previous cells ✔
  • Large regions can be calculated very quickly ✔
  • Instead of adding everything again, we use results that have already been calculated ✔

Connecting This to the Main Problem

In the Dorm Lander problem:

  • we do not calculate only an ordinary sum
  • we calculate a sum weighted by distance

But the basic idea remains the same:

  • we avoid traversing a large number of cells
  • we use precomputed sums
  • we obtain the result in constant time

The Key Intuition

You can think of prefix sums as:

  • "the memory of the matrix"

They store in advance:

  • the sums of previously processed regions
  • so that we do not have to traverse the same cells again later

Connection to Advanced Grid DP

Prefix sums can also optimize more advanced Grid DP problems. In Task 7 below, weighted prefix sums allow us to calculate movement costs in O(1) time for each DP transition.

Practice Problems — Dynamic Programming on a Grid


Task 1: Counting Paths in a 3×3 Grid


A grid of dimensions 3 × 3 is given. The only allowed moves are right and down. Determine how many different paths lead from the top-left to the bottom-right corner.


Task 2: Minimum Path Sum in a 4×4 Grid

A matrix with dimensions 4 × 4 is given:

  • {2, 3, 1, 4}
  • {5, 6, 2, 1}
  • {1, 2, 7, 3}
  • {4, 3, 2, 1}

Determine the minimum path sum from the top-left to the bottom-right corner. Allowed moves: right and down.


Task 3: Grid with Obstacles (5×5)

A 5 × 5 matrix is given, where 0 represents a free cell and 1 represents an obstacle. Allowed moves are to the right and down.


0 0 0 0 0
0 1 0 1 0
0 0 0 0 0
1 0 1 0 0
0 0 0 0 0

Additional Practice Problems (Advanced)


Task 4: Maximum Path Sum in a 4×4 Grid

A matrix with dimensions 4 × 4 is given, containing the following cell values:

  • {1, 2, 3, 4}
  • {2, 1, 4, 3}
  • {3, 2, 1, 2}
  • {4, 3, 2, 1}

Determine the maximum path sum from the top-left to the bottom-right corner. The allowed moves are right and down.

Hint (brief):


dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1])
  
□ Tip: First fill in a small DP table manually to see how the maximum increases.

Task 5: Maximum Path Sum with Obstacles (5×5)

A 5 × 5 matrix is given. The value -1 represents an obstacle that cannot be crossed, while all other cells contain values. The only allowed moves are right and down. Find the maximum sum of cell values along a path from the top-left cell to the bottom-right cell without crossing any obstacles.


0   2   3   4   1
2  -1   1   5   2
3   2  -1   1   3
1   4   2   2   1
2   1   3   1   2

Hint (brief):


dp[0][0] = grid[0][0], if the starting cell is not an obstacle

dp[i][j] = -∞, if grid[i][j] == -1

best = max(dp[i-1][j], dp[i][j-1])
       (cells outside the grid are treated as -∞)

dp[i][j] = grid[i][j] + best, if best != -∞
dp[i][j] = -∞, if best == -∞
Important: If the starting or ending cell is an obstacle, no valid path exists. Report that no path exists instead of automatically setting the result to 0.

Task 6: Competitive Variant — Large Grid and Counting Optimal Paths

A matrix with dimensions 1000 × 1000 is given, with cell values from 0 to 1000. You may move only right or down, from (0,0) to (999,999). Find the number of paths whose sum of cell values is maximum. Since the number of optimal paths can be large, output it modulo 1e9+7.

Hint (brief):


For each cell, store:
- best[i][j]: the maximum path sum to that cell
- ways[i][j]: the number of paths achieving that maximum sum

Compare the best sums from above and from the left.
If both are equal, add their path counts modulo MOD.
For O(m) memory, store only one row of best sums and path counts.
Apply modulo only to the number of paths, not to the maximum sum.
□ Tip: Test the algorithm on a small grid where several paths have the same maximum sum.

Solution-Checking Template — Tasks 4–6


Tasks 4 & 5 — Maximum Path Sum (Small Matrices)

Use this template to check the maximum path sum for a small matrix. A cell containing -1 is an obstacle. The code uses NEG_INF to represent obstacles and unreachable cells.


Checking the DP Table — C++ Template


#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    if (n <= 0 || m <= 0) {
        cout << "Invalid dimensions\n";
        return 0;
    }

    vector<vector<long long>> grid(
        n, vector<long long>(m)
    );

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> grid[i][j];

    const long long NEG_INF =
        numeric_limits<long long>::lowest() / 4;

    vector<vector<long long>> dp(
        n, vector<long long>(m, NEG_INF)
    );

    if (grid[0][0] != -1)
        dp[0][0] = grid[0][0];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (grid[i][j] == -1)
                continue;

            if (i == 0 && j == 0)
                continue;

            long long best = NEG_INF;

            if (i > 0)
                best = max(best, dp[i - 1][j]);

            if (j > 0)
                best = max(best, dp[i][j - 1]);

            if (best != NEG_INF)
                dp[i][j] = best + grid[i][j];
        }
    }

    if (dp[n - 1][m - 1] == NEG_INF)
        cout << "No valid path exists\n";
    else
        cout << dp[n - 1][m - 1] << '\n';

    return 0;
}

Task 6 — Competitive Variant (Large Grid and Modulo)

For a grid with n, m ≤ 1000, count the paths that achieve the maximum possible sum. The code below uses O(m) memory and outputs the number of optimal paths modulo 1e9+7.


Template — C++ (Large Grid)


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const long long MOD = 1000000007LL;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    cin >> n >> m;

    if (n <= 0 || m <= 0) {
        cout << 0 << '\n';
        return 0;
    }

    vector<long long> best(m, 0);
    vector<long long> ways(m, 0);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            long long value;
            cin >> value;

            if (i == 0 && j == 0) {
                best[j] = value;
                ways[j] = 1;
                continue;
            }

            // The value in best[j] is from above.
            long long topBest = (i > 0) ? best[j] : -1;
            long long topWays = (i > 0) ? ways[j] : 0;

            // The value in best[j-1] is from the left.
            long long leftBest = (j > 0) ? best[j - 1] : -1;
            long long leftWays = (j > 0) ? ways[j - 1] : 0;

            if (topBest > leftBest) {
                best[j] = topBest + value;
                ways[j] = topWays;
            } else if (leftBest > topBest) {
                best[j] = leftBest + value;
                ways[j] = leftWays;
            } else {
                best[j] = topBest + value;
                ways[j] = (topWays + leftWays) % MOD;
            }
        }
    }

    cout << ways[m - 1] << '\n';
    return 0;
}

Visual DP Table — Task 5 (Grid with Obstacles)

Obstacles are marked with X. Each cell dp[i][j] represents the maximum path sum from the starting cell (0,0) to cell (i,j), moving only right or down and avoiding obstacles.

i \ j 0 1 2 3 4
0 0 2 5 9 10
1 2 X 6 14 16
2 5 7 X 15 19
3 6 11 13 17 20
4 8 12 16 18 22

How to read the table:
- Cell dp[1][2] = 6 represents the maximum path sum to cell (1,2), avoiding obstacles.
- A cell marked X is an obstacle, so no path can pass through it.
- The destination cell dp[4][4] = 22 gives the maximum path sum from the starting cell to the bottom-right corner.

This table helps students visualize how DP values are calculated, how obstacles block possible paths, and how the maximum sum is propagated through the grid.

Interactive DP Table — Task 5

Hover over a cell to see where its maximum sum comes from.

Advanced Task 7: Dorm Lander — Minimum Total Movement

Advanced challenge: This problem combines dynamic programming with weighted prefix sums. Unlike standard Grid DP problems, we must calculate the total movement cost of all people, rather than simply count paths or minimize the sum of values along a path.

We are given a matrix of dimensions N × M. Each cell a[i][j] contains the number of people located in that cell.

Dorm Lander must choose a path from the top-left corner (1,1) to the bottom-right corner (N,M). The path may move only:

  • Right →
  • Down ↓

After the path is chosen, every person must reach the nearest cell on that path, also moving only right or down. The distance traveled by a person is the number of steps needed to reach the path.

Goal: Find a path that minimizes the sum of the distances traveled by all people.

The formulas and implementation below use 1-based indexing: rows range from 1 to N, and columns range from 1 to M.


Hidden Mini Quiz — Grid DP (2D DP Problem)

Test your understanding of Grid DP, path counting, obstacles, and optimal path problems!

Open quiz

Mini Quiz: Grid DP and Obstacles

1. What is the standard DP recurrence for the maximum path sum in a grid when movement is allowed only right or down and there are no obstacles?





2. In a Grid DP problem that counts paths, what value should dp[i][j] have if cell (i, j) contains an obstacle?





3. In a maximum path sum problem, how can we reconstruct an optimal path after computing the DP table?





4. In a path-counting problem without obstacles, how are the first row and first column initialized when movement is allowed only right or down?





5. What is the time complexity of the standard Grid DP algorithm that calculates each cell once in an n × m grid?





6. Recommended Books and Online Courses