计算Modified Knight在C ++中可以到达的所有可能位置
在本教程中,我们将讨论一个程序,以查找ModifiedKnight可以到达的可能位置。
为此,我们将提供一个8*8的棋盘。我们的任务是找到“改良骑士”可以按照给定步骤数捕获的位置数。
示例
#include <bits/stdc++.h> using namespace std; //寻找职位 void findSteps(int current_row, int current_column,int curr, int board_size, int steps,int* visited){ //边界检查 if (current_row >= board_size || current_row < 0 || current_column >= board_size || current_column < 0 || curr > steps) { return; } if (curr == steps) { *((visited + (current_row)*board_size) + current_column) = 1; return; } findSteps(current_row - 2, current_column - 1,curr + 1, board_size, steps, visited); findSteps(current_row - 2, current_column + 1,curr + 1, board_size, steps, visited); findSteps(current_row - 1, current_column - 2,curr + 1, board_size, steps, visited); findSteps(current_row - 1, current_column - 1,curr + 1, board_size, steps, visited); findSteps(current_row - 1, current_column + 1,curr + 1, board_size, steps, visited); findSteps(current_row - 1, current_column + 2,curr + 1, board_size, steps, visited); findSteps(current_row + 1, current_column - 2,curr + 1, board_size, steps, visited); findSteps(current_row + 1, current_column - 1,curr + 1, board_size, steps, visited); findSteps(current_row + 1, current_column + 1,curr + 1, board_size, steps, visited); findSteps(current_row + 1, current_column + 2,curr + 1, board_size, steps, visited); findSteps(current_row + 2, current_column - 1,curr + 1, board_size, steps, visited); findSteps(current_row + 2, current_column + 1,curr + 1, board_size, steps, visited); return; } int countSteps(int current_row, int current_column,int board_size, int steps){ int visited[board_size][board_size]; for (int i = 0; i < board_size; i++) { for (int j = 0; j < board_size; j++) { visited[i][j] = 0; } } int answer = 0; findSteps(current_row, current_column, 0,board_size, steps, (int*)visited); for (int i = 0; i < board_size; i++) { for (int j = 0; j < board_size; j++) { if (visited[i][j] == 1) { answer++; } } } return answer; } int main(){ int board_size = 8, steps = 1; int current_row = 4, current_column = 4; cout << countSteps(current_row, current_column,board_size, steps); return 0; }
输出结果
12