Distinct Subgrid ValuesMedium

Distinct Subgrid Values

MediumPractice library · +20 XPmatrixprefix sumshash set

Given an N x M grid of integers, for every possible 2 x 2 subgrid, compute the number of distinct integers within that subgrid. Print these counts row by row, from top to bottom, then left to right.

Input

The first line contains two integers N and M (2 <= N, M <= 400). The next N lines each contain M integers, representing the grid. Each integer will be between 1 and 10^9.

Output

Print (N-1) * (M-1) integers, representing the number of distinct values in each 2x2 subgrid. The counts should be printed row by row, from top to bottom, then left to right.

Constraints

2 <= N, M <= 400. Grid elements are between 1 and 10^9.

Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests

Example 1

Input
3 4
1 2 3 4
5 1 2 3
2 3 4 1
Output
3 3 3 4 4 4

The 2x2 subgrids are [[1,2],[5,1]], [[2,3],[1,2]], [[3,4],[2,3]], [[5,1],[2,3]], [[1,2],[3,4]], [[2,3],[4,1]]. Their distinct counts are 3, 3, 3, 4, 3, 4.

Example 2

Input
2 2
10 20
30 10
Output
3

There is only one 2x2 subgrid [[10,20],[30,10]], containing distinct values 10, 20, 30. The count is 3.

Hints