在 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