15103 - Bangboo path verify   

Description

Ms. Sunbringer created a special kind of robot designed spefically for Hollow exploration and presented it to Joyous. The Hollow is a special location where space are distorted to the extreme, making people lost if they accidentally got in one. This Bangboo robot has a special kind of data built into it called a Carrot Data that can help you navigate the Hollow without getting lost. Your job right now is to help Ms. Sunbringer verify that Carrot Data by calculating the length of the longest increasing path in a matrix. 

You are given an R × C integer matrix.

Starting from any cell, you may move to one of its four neighbouring cells (up, down, left, or right).

You may only move to a neighbouring cell whose value is strictly greater than the value of the current cell. Diagonal moves and moves outside the matrix are not allowed.

An increasing path is a sequence of cells whose values are strictly increasing

For example:

9 9 4
6 6 8
2 1 1

One possible longest increasing path is:

1 → 2 → 6 → 9

The length of this path is 4.

Your task is to find and print the length of the longest increasing path in the matrix.

Note that the length of a path is measured by the number of cells it contains, not the number of moves.

How the algorithm works

To aid you with this task, Ms. Sunbringer also gives you the description of how the algorithm works

Step 1 - Recursive DFS

Let dfs(r, c) represent the length of the longest increasing path starting from cell (r, c).

Starting from the current cell:

  • Examine its four neighbouring cells.

  • Move only to valid neighbours with strictly greater values.

  • Recursively explore the possible paths and determine the longest one.

Since a path may start from any cell, every cell should be considered as a possible starting point.

However, different paths may reach the same cell, causing the same subproblem to be solved repeatedly.

dfs(r, c):
    best = 1
    for each neighbour (nr, nc): # Four neighbuoring cells
        if (nr, nc) is inside the matrix:
            if matrix[nr][nc] > matrix[r][c]:
                best = max(best, 1 + dfs(nr, nc))
    return best

Step 2 - Avoid repeated computation

The result of dfs(r, c) depends only on the current cell, regardless of how the path reaches it.

Instead of repeatedly computing the same result, the answer for the a cell can be computed once, saved, and reused.

So use a table  memo with the same shape as the matrix:

  1. Inititally, the memo table filled with 0  which indicates that the result has not been computed.
  2. At the starts of dfs(r, c) : if memo(r, c) != 0, return the stored result immediately

  3. Otherwise compute the answer using the neighbours (recursively)

  4. Store the computed answer into memo(r, c) before returning it.

Example - Memoization Table

  • memo[0][0] = 1: No valid increasing move is available.

  • memo[2][0] = 3: The longest increasing path starting from this cell is 2 → 6 → 9.

  • memo[2][1] = 4: The longest increasing path starting from this cell is 1 → 2 → 6 → 9.

The final answer is the largest value in the memoization table, which is 4.

Complexity

 Category  Without memo  With memo
 Time  exponential (worst case)  O(R*C) - each cell computed
 Space  O(R*C) recursion  O(R*C) memo + O(R*C) recursion depth

Starter code

def dfs(r, c):
    # TODO 1: Check whether the result has already been computed.
    best = 1
    for dr, dc in directions:
        nr, nc = r + dr, c + dc
        if 0 <= nr < R and 0 <= nc < C:
            if matrix[nr][nc] > matrix[r][c]:
                # TODO 2: Recursively explore this neighbour
                # and update best.
                pass
    # TODO 3: Store the computed result in the memoization table.
    return best

def longest_increasing_path():
    answer = 0
    for r in range(R):
        for c in range(C):
            # TODO 4: Consider the path starting at this cell
            # and update answer.
            pass
    return answer

if __name__ == "__main__":
    R, C = map(int, input().split())
    matrix = [list(map(int, input().split())) for _ in range(R)]

    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    print(longest_increasing_path())

Input

The first line contains two integers R, C, representing the number of rows, the number of columns.

The next R lines each contain C integers representing the matrix.

R C
a11 a12 ... a1C
...
aR1 aR2 ... aRC

Constraints

  • 1 ≤ R, C ≤ 200

  • −10⁹ ≤ matrix[r][c] ≤ 10⁹

  • Stack depth up to R*C=40000 can occur (e.g. a snake-like increasing path).

Output

One integer: the length of the longest increasing path.

Sample Input  Download

Sample Output  Download




Discuss