Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-256

Stencil Operator Apply

Problem

Apply the 5-point Laplacian stencil to a 2D grid u with zero Dirichlet boundary:

(Au)[i][j] = 4*u[i][j] - u[i-1][j] - u[i+1][j] - u[i][j-1] - u[i][j+1]

Out-of-grid neighbors are treated as 0. Return the resulting matrix.

Hint

The stencil is the discrete counterpart of the 2D Laplacian operator.

Test cases

case 1
in: [[[1]]]
expected: [[4]]
case 2
in: [[[1,0],[0,0]]]
expected: [[4,-1],[-1,0]]
case 3
in: [[[0,0],[0,0]]]
expected: [[0,0],[0,0]]
case 4
in: [[[1,1],[1,1]]]
expected: [[2,2],[2,2]]
Starter codePython
def apply_laplacian_stencil(u):
    # Your code here
    pass

4 test cases · run your code against them in the editor