Largest Local Values in a Matrix

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
        # The dimensions of the new matrix are 2 less than the original matrix
        n = len(grid) - 2
        maxLocal = [[0]*n for _ in range(n)]

        # Loop through the grid matrix
        for i in range(n):
            for j in range(n):
                # For each cell in the maxLocal matrix, extract the corresponding 3x3 grid
                local_grid = []
                for x in range(3):
                    for y in range(3):
                        local_grid.append(grid[x+i][y+j])
                # And find the maximum element in the 3x3 grid
                maxLocal[i][j] = max(local_grid)

        return maxLocal