บนกระดานหมากรุกขนาด 8×8 กำหนดตำแหน่งของบิชอป (Bishop) ในรูปแบบแถวและคอลัมน์ เป้าหมายคือหาจำนวนช่องทั้งหมดที่บิชอปสามารถเดินไปได้ในหนึ่งนัด เรารู้ว่าบิชอปเดินได้ทุกทิศทาง (เฉียงซ้ายบน/ล่าง และขวาบน/ล่าง)

ตัวอย่าง
Input
row = 5, column = 4
Output
Count of total number of squares that can be visited by Bishop in one move are: 13
Explanation
As shown in above figure the squares that Bishop can cover are 9.
Input
row = 1, column = 1
Output
Count of total number of squares that can be visited by Bishop in one move are: 7
Explanation
As this is the corner most position, then Bishop can only cover one diagonal which can have a maximum of 7 squares.
วิธีการที่ใช้ในโปรแกรม
วิธีนี้คำนวณช่องเฉียงโดยใช้ตำแหน่งแนวนอนและแนวตั้งสูงสุดและต่ำสุด
- รับจำนวนเต็ม
rowและcolumnสำหรับตำแหน่งบิชอป - ฟังก์ชัน
squares_visited(int first, int second)คืนค่าจำนวนช่องที่บิชอปเดินได้ในหนึ่งนัด - กำหนดจำนวนนับเริ่มต้นเป็น 0
- ตำแหน่งขวาสูงสุดด้านซ้าย:
min_left = min(first, second) - 1 - ตำแหน่งขวาสูงสุดด้านซ้าย:
max_left = 8 - max(first, 9 - second) - ตำแหน่งขวาสูงสุดด้านขวา:
max_right = 8 - max(first, second) - ตำแหน่งขวาต่ำสุดด้านขวา:
min_right = min(first, 9 - second) - 1 - จำนวนช่องทั้งหมด = ผลรวมของค่าที่คำนวณได้ทั้ง 4 ค่า
- คืนค่า count เป็นผลลัพธ์
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
int squares_visited(int first, int second){
int count = 0;
int min_left = min(first, second) - 1;
int max_left = 8 - max(first, 9 - second);
int max_right = 8 - max(first, second);
int min_right = min(first, 9 - second) - 1;
count = min_left + min_right + max_right + max_left;
return count;
}
int main(){
int row = 3, column = 3;
cout << "Count of total number of squares that can be visited by Bishop in one move are: " << squares_visited(row, column);
return 0;
}
Output
หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:
Count of total number of squares that can be visited by Bishop in one move are: 11