0

I tried knight Tour problem, although the code looks correct only still I am not getting the correct answer always it is returning -1 i.e no solution exists. I have defined few functions first one is select that returns the pair for next move for knight which is then added to respective i and j values. Then I have validate function that checks if the next move is correct or not if not than for loop iterates further else if true than backtracking happens.

def select(k):
    list1=[2, 1, -1, -2, -2, -1, 1, 2]
    list2=[1, 2, 2, 1, -1, -2, -2, -1]
    return list1[k],list2[k]    

def validate(chessBoard,i,j):
    if((i>=0)and(i<8)and (j>=0)and(j<8)and(chessBoard[i][j]==0)):
        return 1
    return -1   


def knightTour(chessBoard,total,i,j):
    if(total==64):
        for x in range(0,8):
            print("\n")
            for y in range(0,8):
                print(chessBoard[i][j],end=" ")
        return 1
    else:
        for k in range(0,8):
            row,column=select(k)
            i,j=row+i,column+j
            if(validate(chessBoard,i,j)==1):
                total=total+1
                chessBoard[i][j]=total
                check=knightTour(chessBoard,total,i,j)
                if(check==1):
                    return 1
                total=total-1       
                chessBoard[i][j]=0
    return -1           

#main function

chessBoard=[[1,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0,0]
            ]
total=0
i,j=0,0
knightTour(chessBoard,total,i,j)
false
  • 10,264
  • 13
  • 101
  • 209
Hritik Sharma
  • 69
  • 1
  • 5

1 Answers1

0

You need to reset i and j after the if that uses validate in your for loop.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101