# Kth Manhattan Distance Neighbourhood

Given a matrix M of size nxm and an integer K, find the maximum element in the K manhattan distance neighbourhood for all elements in nxm matrix.\
In other words, for every element M\[i]\[j] find the maximum element M\[p]\[q] such that `abs(i-p)+abs(j-q) <= K`.

`Note: Expected time complexity is O(N*N*K)`

**Constraints:**

```
1 <= n <= 300
1 <= m <= 300
1 <= K <= 300
0 <= M[i][j] <= 1000
```

**Example:**

```
Input:
M  = [[1,2,4],[4,5,8]] , K = 2

Output:
ans = [[5,8,8],[8,8,8]]
```

```java
public class Solution {
    public int[][] solve(int K, int[][] matrix) {
        int n = matrix.length, m = matrix[0].length, min = Integer.MIN_VALUE;
        int[][][] dp = new int[K + 1][n][m];
        for (int k = 0; k <= K; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (k == 0)
                        dp[k][i][j] = matrix[i][j];
                    else {
                        int cur = min;
                        if (i > 0)
                            cur = Math.max(cur, dp[k - 1][i - 1][j]);
                        if (j > 0)
                            cur = Math.max(cur, dp[k - 1][i][j - 1]);
                        if (i < n - 1)
                            cur = Math.max(cur, dp[k - 1][i + 1][j]);
                        if (j < m - 1)
                            cur = Math.max(cur, dp[k - 1][i][j + 1]);
                        dp[k][i][j] = Math.max(cur, dp[k - 1][i][j]);
                    }
                }
            }
        }
        int[][] ans = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                ans[i][j] = dp[K][i][j];
        return ans;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/dynamic-programming/kth-manhattan-distance-neighbourhood.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
