mercredi 8 décembre 2021

backtracking problem - i am not getting any output - (wanderdoff's algorithm)

can anyone help me out with this knights tour problem ! the code is just taking in values from the user and there is no output. i am a beginner though , i just learnt the concept of backtracking and just coded everything that came to my mind , so please tell what is the issue

#include <iostream>
using namespace std;
int xmove[] = {2 , 1 , -1 , -2 , 2 , 1 , -1 , -2 };
int ymove[] = {1 , 2 , 2 , 1 , -1 , -2 , -2 , -1};
bool knight(int **arr , int x , int y , int n , int pos){
    if(x == n && y == n){
        return true;
    }
    if(arr[x][y] == 0 && pos<=n*n && x < n && y < n){
        arr[x][y] = pos;
        for(int i=0 ; i<8 ; i++){
            if(knight(arr , x+xmove[i] , y+ymove[i] , n , pos+1)){
                return true;
            }else{
                arr[x][y] = 0;
                return false;
            }
        }
    }
    return false;
}
int main(){
    int n ; cin >> n;
    int **arr = new int*[n];
    for(int i=0 ; i<n ; i++){
        arr[i] = new int[n];
    }
    for(int i=0 ; i<n ; i++){
        for(int j=0 ; j<n ; j++){
            arr[i][j] = 0;
        }
    }
    if(knight(arr , 0 , 0 , n , 0)){
        for(int i=0 ; i<n ; i++){
            for(int j=0 ; j<n ; j++){
                cout << arr[i][j] << " ";
            }cout << endl;
        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire