用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

更新於:2021年1月5日

686 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.