On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces.
You are given N bishops, represented as (row, column) tuples on an M by M chessboard. Write a function to count the number of pairs of bishops that attack each other. The ordering of the pair doesn’t matter: (1, 2) is considered the same as (2, 1).
Input: M =5, bishops =[[0,0],[1,2],[2,2,],[4,0]]Output: 2Explanation: Bishops 1 and 3 attack each other, as well as bishops 3 and 4.This is how the board look with bishops:[b 0000][00 b 00][00 b 00][00000][b 0000]
Bishops can attack diagonally in two directions: from the top-left to the bottom-right (referred to here as positive diagonals, where i - j is constant) and from the top-right to the bottom-left (referred to here as negative diagonals, where i + j is constant).
Identify Diagonals: We’ll use two hashmaps to track the number of bishops on each of the two types of diagonals.
Count Pairs: For each diagonal, if there are k bishops, the number of pairs of bishops that attack each other on that diagonal is given by the combination formula C(k, 2) = k * (k - 1) / 2.
Here are the steps:
Create two hashmaps:
One for the positive diagonals.
One for the negative diagonals.
For each bishop, update the count in both hashmaps.
Sum the pairs from both hashmaps using the combination formula.