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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP