Sum of the count of number of adjacent squares in an M X N grid
Given an M × N matrix. The task is to count the number of adjacent cells and calculate their sum.
Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally.
Input : m = 2, n = 2
Output : 12
Input : m = 3, n = 2
See the below diagram where numbers written on it denotes number of adjacent squares.
In a m X n grid there can be 3 cases:
- Corner cells touch 3 cells, and there are always 4 corner cells.
- Edge cells touch 5 cells, and there are always 2 * (m+n-4) edge cells.
- Interior cells touch 8 cells, and there are always (m-2) * (n-2) interior cells.
Sum = 3*4 + 5*2*(m+n-4) + 8*(m-2)*(n-2) = 8mn - 6m - 6n +4
Below is the implementation of the above approach:
Auxiliary Space: O(1)