在C++中统计改良骑士可达的所有可能位置


在本教程中,我们将讨论一个程序,用于查找改良骑士可达的所有可能位置。

为此,我们将获得一个 8*8 的棋盘。我们的任务是根据给定的步数找出改良骑士可以占领的位置数。

示例

#include <bits/stdc++.h>
using namespace std;
//finding the positions
void findSteps(int current_row, int current_column,int curr, int board_size, int steps,int* visited){
   //bound checking
   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

更新时间: 10-Feb-2020

73 次浏览

开启您的 职业生涯

完成课程,获得认证

开始
广告