Valid Two-Dimensional Convolution
Problem statement
For this exercise, use true two-dimensional convolution: flip the kernel in both directions, slide it over the image with stride 1, and use no padding. Return only positions where the entire kernel fits. Leave both inputs unchanged.
For a kernel of height H and width W, the output entry at [r][c] is the sum of image[r+u][c+v] * kernel[H-1-u][W-1-v] over all kernel offsets u and v. The output has image.length-H+1 rows and image[0].length-W+1 columns. This orientation differs from unflipped cross-correlation.
Function
convolve2D(image: int[][], kernel: int[][]) → int[][]Examples
Example 1
image = [[1,2,3],[4,5,6]]kernel = [[1,2]]return = [[4,7],[13,16]]The kernel flips from [1,2] to [2,1]. The first two sums are 1*2+2*1=4 and 2*2+3*1=7. The second image row gives 13 and 16.
Example 2
image = [[1,2],[3,4]]kernel = [[1,2],[3,4]]return = [[20]]The flipped kernel is [[4,3],[2,1]]. The only valid sum is 1*4+2*3+3*2+4*1=20.
Constraints
1 <= image.length, kernel.length <= 16.1 <= each image row length, each kernel row length <= 16.-10 <= every matrix value <= 10.- Both matrices are nonempty and rectangular. The kernel height and width do not exceed the image height and width.