在 C++ 中检查国王在修改后的棋盘上有 N 个骑士的情况下是否可以进行有效移动
概念
对于给定的无限棋盘,其规则与国际象棋相同,并且给定 N 个骑士在无限棋盘上的坐标(-10^9 <= x, y <= 10^9)以及国王的坐标,任务是验证国王是否处于将死状态。
输入
a1[] = { { 2, 1 }, { 1, 3 }, { 3, 6 },{ 5, 5 }, { 6, 1 }, { 7, 3 }} king -> {4, 3}输出
Yes
国王无法移动,因为它已被将死。
输入
a1 [] = {{1, 1}} king -> {3, 4}输出
No
国王可以进行有效移动。
方法
这里,骑士的移动在棋子中是不寻常的。它的移动方向是水平方向移动两个方格,垂直方向移动一个方格,或者垂直方向移动两个方格,水平方向移动一个方格。因此,完整的移动看起来像“L”形,以所有可能的形状(8 种可能的移动方式)。因此,应用成对的哈希映射来标记骑士可以移动的所有可能的坐标。如果发现国王无法移动到其附近的 8 个坐标中的任何一个,即如果该坐标被骑士的移动哈希化,则将其声明为“将死”。
示例
// C++ program for verifying if a king
// can move a valid move or not when
// N nights are there in a modified chessboard
#include <bits/stdc++.h>
using namespace std;
bool checkCheckMate1(pair<int, int>a1[], int n1, int kx1, int ky1){
// Pair of hash to indicate or mark the coordinates
map<pair<int, int>, int> mpp1;
// iterate for Given N knights
for (int i = 0; i < n1; i++) {
int x = a1[i].first;
int y = a1[i].second;
// indicate or mark all the "L" shaped coordinates
// that can be reached by a Knight
// starting or initial position
mpp1[{ x, y }] = 1;
// 1-st move
mpp1[{ x - 2, y + 1 }] = 1;
// 2-nd move
mpp1[{ x - 2, y - 1 }] = 1;
// 3-rd move
mpp1[{ x + 1, y + 2 }] = 1;
// 4-th move
mpp1[{ x + 1, y - 2 }] = 1;
// 5-th move
mpp1[{ x - 1, y + 2 }] = 1;
// 6-th move
mpp1[{ x + 2, y + 1 }] = 1;
// 7-th move
mpp1[{ x + 2, y - 1 }] = 1;
// 8-th move
mpp1[{ x - 1, y - 2 }] = 1;
}
// iterate for all possible 8 coordinates
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
int nx = kx1 + i;
int ny = ky1 + j;
if (i != 0 && j != 0) {
// verify or check a move can be made or not
if (!mpp1[{ nx, ny }]) {
return true;
}
}
}
}
// any moves
return false;
}
// Driver Code
int main(){
pair<int, int&lgt; a1[] = { { 2, 1 }, { 1, 3 }, { 3, 6 }, { 5, 5 }, { 6, 1 }, { 7, 3 }};
int n1 = sizeof(a1) / sizeof(a1[0]);
int x = 4, y = 3;
if (checkCheckMate1(a1, n1, x, y))
cout << "Not Checkmate!";
else
cout << "Yes its checkmate!";
return 0;
}输出
Yes its checkmate!
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP