Count all possible position that can be reached by Modified Knight in C++



In this tutorial, we will be discussing a program to find the number of possible positions that can be reached by Modified Knight.

For this we will be provided with a 8*8 chessboard. Our task is to find the number of positions Modified Knight can capture with the given number of steps.

Example

#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; }

Output

12
Updated on: 2020-02-10T12:13:17+05:30

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements