首页 文章资讯内容详情

C ++中骑士的可能动作

2026-06-05 1 花语

在这个问题中,给我们一个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