![]() |
VOOZH | about |
Given two integers, n and m, denoting dimensions of a chessboard. The task is to count ways to place a black and a white knight on an n * m chessboard such that they do not attack each other. The knights have to be placed on different squares.
Note: A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move.
👁 ImageExamples:
Input: n = 2, m = 2
Output: 12
Explanation: The first Kniight can be placed in any of the 4 cells and the second knight can be be placed in any of the remaining 3 cells. For a Knight to attack. one dimension must be at least 3.Input: n = 2, m = 3
Output: 26
Table of Content
The idea is to count total ways to place two knights on the board and subtract the number of attacking pairs. For every cell, we calculate how many valid knight moves it can make (only in one direction set to avoid double counting).
26
The arrangements attacks where knight to move 2 steps in the horizontal direction and 1 step in the vertical. to 4 * (n - 2) * (m - 1) and similarly for 2 steps in the vertical direction and 1 step in the horizontal. Thus the answer will be Total possible arrangement - 4 * (n - 2) * (m - 1) - 4 * (n - 1) * (m - 2) which is (n*m)*(n*m - 1) - 4 * (n - 2) * (m - 1) - 4 * (n - 1) * (m - 2)
How does this work?
26