C++ 中騎士的可能走法


在這個問題中,我們給定一個 m*n 的棋盤,其中填充的位置用 1 表示,即如果 board[i][j] = 1,則該位置有棋子,並且給定起始位置。我們的任務是在棋盤上找到騎士的所有可能走法總數,如果所有棋子都是同一種顏色,即不會發生攻擊。

國際象棋中的騎士是一種可以向所有方向移動的棋子,並且具有特殊的移動方式。

  • 橫向移動兩格,縱向移動一格。

  • 縱向移動兩格,橫向移動一格。

讓我們舉個例子來理解這個問題:

**輸入** -

board[][] = {
   { 0, 1, 0, 0 },
   { 0, 0, 1, 1 },
   { 0, 1, 1, 0 },
   { 0, 0, 0, 1 }
};
Position : (1,1)

**輸出** - 4

為了解決這個問題,我們需要找到在棋盤上騎士所有可能走法中哪些是有效的走法。如果移動到棋盤上的一個位置,並且該位置沒有被其他棋子佔用,則該移動是有效的。

為此,我們將儲存從給定位置開始騎士的所有可能走法。然後檢查每種走法的有效性,併為每種有效走法增加計數。

示例

展示我們解決方案實現的程式 -

 線上演示

#include <bits/stdc++.h>
#define N 8
#define M 8
using namespace std;
int countPossibleMoves(int mat[N][M], int p, int q){
   int Xmoves[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
   int Ymoves[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
   int count = 0;
   for (int i = 0; i < 8; i++) {
      int x = p + Xmoves[i];
      int y = q + Ymoves[i];
      if (x>=0 && y>=0 && x<N && y<M && mat[x][y]==0)
         count++;
   }
   return count;
}
int main(){
   int mat[N][M] = { { 0, 1, 0, 0 },
      { 0, 0, 1, 1 },
      { 0, 1, 1, 0 },
      { 0, 0, 0, 1 }};
   int position[2] = {1,1};
   cout<<"Total number of moves possible for Knight from position ("<<position[0]<<" , "<<position[1]<<") are : ";
   cout<<countPossibleMoves(mat, position[0], position[1]);
   return 0;
}

輸出

Total number of moves possible for Knight from position (1 , 1) are : 4

更新於: 2020-04-17

886 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

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