JustJustin

Knights Tour

Mar 12th, 2012
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #Knights tour time
  2. import operator
  3.  
  4. def valid(n,  m,  tour,  place):
  5.     return place[0] < n and place[0] >= 0 and place[1] < m and place[1] >= 0 and place not in tour
  6.  
  7. def knights_tour(n,  m,  tour):
  8.     placements = [ [-2,  -1],  [-2,  1], [-1,  -2],  [-1,  2],  [1,  -2],  [1,  2],  [2, -1],  [2, 1]]
  9.     if len(tour) == n * m:
  10.         for place in [map(operator.add,  tour[-1],  i) for i in placements]:
  11.             if place == tour[0]:
  12.                 print "Open Tour"
  13.         return tour
  14.     #Find valid placement, greedy
  15.     weighteddegree = 9
  16.     weightedplace = []
  17.     for place in [map(operator.add,  tour[-1],  i) for i in placements]:
  18.         if valid(n,  m,  tour,  place):
  19.             degree = sum([valid(n,  m,  tour,  j) for j in [map(operator.add,  place,  ii) for ii in placements]])
  20.             if degree < weighteddegree:
  21.                 weightedplace = place
  22.                 weighteddegree = degree
  23.    
  24.     if weighteddegree < 9:
  25.         tour.append(weightedplace)
  26.         return knights_tour(n,  m,  tour)
  27.    
  28.     return False
  29.    
  30. def print_board(n,  m,  tour):
  31.     placements = [ [-2,  -1],  [-2,  1], [-1,  -2],  [-1,  2],  [1,  -2],  [1,  2],  [2, -1],  [2, 1]]
  32.     for y in range(n):
  33.         for x in range(m):
  34.             if [y,  x] in tour:
  35.                 print "K",
  36.             else:
  37.                 print sum([valid(n,  m,  tour,  j) for j in [map(operator.add,  [y,  x],  ii) for ii in placements]]),
  38.         print
  39.    
  40. def helper(n,  m):
  41.     for i in range(n):
  42.         for j in range(m):
  43.             print("Knights Tour at " + str(i) + "," + str(j))
  44.             ret = knights_tour(n,  m,  [[i ,  j]])
  45.             print(ret)
  46.    
  47. def main():
  48.     print("Knights Tour")
  49.     n = int(raw_input("Board Height:"))
  50.     m = int(raw_input("Board Widtht:"))
  51.    
  52.     while True:
  53.         i = int(raw_input("Start Row:"))
  54.         j = int(raw_input("Start Column:"))
  55.         if i < 0 or j < 0 or i >= n or j >= m:
  56.             print("Invalid start position, note that 0 is a valid column/row.")
  57.         else:
  58.             break
  59.    
  60.     #helper(n,  m)
  61.    
  62.     ret = knights_tour(n,  m,  [[i ,  j]])
  63.     print(ret)
  64.  
  65. main()
Advertisement
Add Comment
Please, Sign In to add comment