#P9582. Good Friends in Grid
Good Friends in Grid
Good Friends in Grid
Given a grid with \(n\) rows and \(m\) columns, where the cell in the \(i\)-th row and \(j\)-th column contains the number \(a_{i,j}\), two cells are considered adjacent if they share a common edge. Two distinct cells are good friends if and only if they are not adjacent and the numbers in these cells are equal.
Your task is to compute the sum of the number of good friends for all cells in the grid. Note that if two cells are good friends, each cell considers the other as a friend.
Hint: If for a particular number, there are \(k\) occurrences in the grid, the total number of ordered pairs of cells with that number is \(k \times (k-1)\). However, if two cells are adjacent (share an edge) they cannot be good friends. For every pair of adjacent cells having the same value, subtract 2 from the total (since both cells would have counted each other).
inputFormat
The first line contains two integers \(n\) and \(m\) (the number of rows and columns, respectively).
Each of the next \(n\) lines contains \(m\) integers representing the grid. The \(j\)-th integer in the \(i\)-th line is \(a_{i,j}\).
outputFormat
Output a single integer representing the total sum of good friends counts of all the cells.
sample
2 2
1 2
2 1
4