Skip to content

Instantly share code, notes, and snippets.

@domarps
Created April 7, 2018 22:26
Show Gist options
  • Save domarps/cf15c910a9f78a207117ef1bdb32d928 to your computer and use it in GitHub Desktop.
Save domarps/cf15c910a9f78a207117ef1bdb32d928 to your computer and use it in GitHub Desktop.
knight's tour on a chessboard
import queue
class knightsTour:
def __init__(self):
pass
def is_within_limits(self, i, j, M, N):
'''
:param i
:param j
:param M
:param N
'''
if i >= 0 and j >= 0 and i < M and j < N:
return True
return False
def knight_tour(self, M, N, st, ed):
'''
:param M : rows of chess board
:param N : cols of chess board
:param st : co-ordinates of source point
:param ed : co-ordinates of destination point
'''
if st == ed:
return 0
# 8 potential moves a knight can make!
moves = [(-2,1), (2,1), (2,-1), (-2,-1), (1,2), (1,-2), (-1,2), (-1, -2)]
# we keep track of the shortest distances from the start point
distance = [[-1 for _ in range(N)] for _ in range(M)]
# initialize the queue with the starting cell, st
bfs_q = queue.Queue()
bfs_q.put(st)
# initialize the start point to be 0 distance
distance[st[0]][st[1]] = 0
while not bfs_q.empty():
curr_pos = bfs_q.get()
# if we are at the end cell, break!
if curr_pos == ed:
break
for move in moves:
neighbor_x, neighbor_y = curr_pos[0] + move[0], curr_pos[1] + move[1]
# if this is valid neighbor and the neighbor has not been visited yet!
if self.is_within_limits(neighbor_x, neighbor_y, M, N) and distance[neighbor_x][neighbor_y] == -1:
distance[neighbor_x][neighbor_y] = distance[curr_pos[0]][curr_pos[1]] + 1
bfs_q.put((neighbor_x, neighbor_y))
return distance[ed[0]][ed[1]]
k = knightsTour()
assert k.knight_tour(33333,3, (333,0), (33332,2)) == 16501
assert k.knight_tour(3, 33332, (1,1599), (1,0)) == 801
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment