LeetKernels
ProblemsStart solving
Problems

69. 2D Jacobi Stencil medium

Given a 2D grid of 32-bit floating point values, apply one iteration of the 5-point Jacobi stencil: each interior cell of the output is set to the average of its four cardinal neighbors (top, bottom, left, right) from the input grid. Boundary cells (first/last row and column) are copied unchanged from the input to the output.

5-Point Jacobi Stencil T L (2,2) R B Center cell Neighbors Boundary output[i,j] = ¼ × (top + bottom + left + right)

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in output
  • Read exclusively from input and write exclusively to output (do not update input)

Example:

Input (4×4): ​1.05.09.013.0​2.06.010.014.0​3.07.011.015.0​4.08.012.016.0​​ Output (4×4): ​1.05.09.013.0​2.06.010.014.0​3.07.011.015.0​4.08.012.016.0​​ Interior cell (1,1): 0.25×(input[0,1]+input[2,1]+input[1,0]+input[1,2]) =0.25×(2.0+10.0+5.0+7.0)=6.0
Interior cell (1,2): 0.25×(input[0,2]+input[2,2]+input[1,1]+input[1,3]) =0.25×(3.0+11.0+6.0+8.0)=7.0
Interior cell (2,1): 0.25×(input[1,1]+input[3,1]+input[2,0]+input[2,2]) =0.25×(6.0+14.0+9.0+11.0)=10.0
Interior cell (2,2): 0.25×(input[1,2]+input[3,2]+input[2,1]+input[2,3]) =0.25×(7.0+15.0+10.0+12.0)=11.0

Constraints

  • 1 ≤ rows, cols ≤ 16,384
  • Input values are in the range [-100, 100]
  • All values are 32-bit floats
  • Performance is measured with rows = 8,192, cols = 8,192

Starter code (CUDA)

#include <cuda_runtime.h>

// input, output are device pointers
extern "C" void solve(const float* input, float* output, int rows, int cols) {}

Solve it on your GPU

Previous: Sigmoid ActivationNext: Segmented Exclusive Prefix Sum

From LeetGPU, CC BY-NC-ND 4.0.