用C++计算主教一步能访问的方格总数
在一个以8x8网格表示的棋盘上,我们得到主教的行和列位置。目标是找到主教一步能访问的方格总数。我们知道主教可以向所有方向移动(对角线左上/下和右上/下)。

例如
输入
row = 5, column = 4
输出
Count of total number of squares that can be visited by Bishop in one move are: 13
解释
As shown in above figure the squares that Bishop can cover are 9.
输入
row = 1, column = 1
输出
Count of total number of squares that can be visited by Bishop in one move are: 7
解释
As this is the corner most position, then Bishop can only cover one diagonal which can have a maximum of 7 squares.
以下程序中使用的算法如下 −
在这种方法中,我们将使用水平和垂直最大和最小方格位置来计算对角线方格。
获取主教位置的整数行和列。
函数squares_visited(int first, int second) 获取主教的位置并返回它一步能访问的方格数。
将初始计数设置为0。
左侧位置的最小值是行或列位置的最小值 −1。
左侧位置的最大值是 8 − 行或 9−列位置的最大值。
右侧位置的最小值是行或 9−列位置的最小值 −1。
右侧位置的最大值是 8 − 行或列位置的最大值。
总方格数将是上述计算位置的总和。
返回计数作为结果。
示例
#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;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count of total number of squares that can be visited by Bishop in one move are: 11
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP