'What is the logic behind calculating diagonals on a chessboard?

Given the position of a Bishop on an 8 * 8 chessboard, the task is to count the total number of squares that can be visited by the Bishop in one move. The position of the Bishop is denoted using row and column number of the chessboard.

Examples:

Input: Row = 4, Column = 4 Output: 13 Input: Row = 1, Column = 1 Output: 7

Approach: In the game of chess, a Bishop can only move diagonally and there is no restriction in distance for each move.

So, We can also say that Bishop can move in four ways i.e. diagonally top left, top right, bottom left and bottom right from current position.

We can calculate the numbers of squares visited in each move by:

Total squares visited in Top Left move = Math.min(r, c) – 1

Total squares visited in Top Right move = Math.min(r, 9 – c) – 1

Total squares visited in Bottom Left move = 8 – Math.max(r, 9 – c)

Total squares visited in Bottom Right move = 8 – Math.max(r, c)

where, r and c are the coordinates of the current position of the Bishop on the chessboard.

Guys I cannot figure out the logic behind the above diagonal calculations. Please help me find out that by what logic the diagonals are calculated above ??? I JUST NEED THE LOGIC. No code required.

( Also If you can help with the basic behind logic of similar kinds of chess problems or matrix it would be fantastic)

Chessboard image for reference



Solution 1:[1]

The top-left distance to the edge of the board is indeed min(r, c) - 1. Given that the bishop starts on rank r, it can move up no more than r - 1 ranks before landing on the first rank. It may hit the first file before that if c < r, in which case it will only be able to move c - 1 squares. For example if the bishop starts at r = 5 and c = 4, it will be able to move three squares, not four. Thus the top-left formula is min(r - 1, c - 1), which can be refactored to min(r, c) - 1.

Similarly, when heading towards the bottom-left corner, the rank increases while the file decreases. The bishop can move at most 8 - r ranks and at most c - 1 files, so the bottom-left formula is min(8 - r, c - 1). That can be refactored to 8 – max(r, 9 – c), although this expression seems more convoluted.

Solution 2:[2]

To count elements in the left-top and right-bottom sides of the diagonal (in which Bishop is placed), the following formula is enough: n-abs(r-c)-1, where n is the size of the board e.g. n=8 in the above case.

So three (instead of four) formulae can give all the cells that Bishop can visit diagonally: [8-abs(r-c)-1] + [Math.min(r, 9 – c) – 1] + [8 – Math.max(r, 9 – c)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 C?t?lin Frâncu
Solution 2 user13934743