from graph import * def knightGraph(bdSize): def posToNodeId(r, c, s): return r*s+c ktGraph = Graph() # Build the graph for row in range(bdSize): for col in range(bdSize): nodeId = posToNodeId(row, col, bdSize) newPositions = genLegalMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) return ktGraph def genLegalMoves(x, y, bdSize): newMoves = [] moveOffsets = [(-1,-2), (-1,2), (-2,-1), (-2,1), ( 1,-2), ( 1,2), ( 2,-1), ( 2,1)] for i in moveOffsets: newX = x + i[0] newY = y + i[1] if legalCoord(newX, bdSize) and \ legalCoord(newY, bdSize): newMoves.append((newX, newY)) return newMoves def legalCoord(x, bdSize): if x >= 0 and x < bdSize: return True else: return False def knightTour(n, path, u, limit): u.setColor('gray') path.append(u) if n < limit: nbrList = orderByAvail(u) i = 0 done = False while i < len(nbrList) and not done: if nbrList[i].getColor() == 'white': done = knightTour(n+1, path, nbrList[i], limit) if not done: # prepare to backtrack path.remove(u) u.setColor('white') else: done = True return done def orderByAvail(n): resList = [] for v in n.getAdj(): if v.getColor() == 'white': c = 0 for w in v.getAdj(): if w.getColor() == 'white': c = c + 1 resList.append((c, v)) resList.sort() return [y[1] for y in resList] def run(): G = knightGraph(8) path = [] assert(knightTour(0, path, G.vertList[0], 63)) def nodeIdToPos(n): return (n/8, n%8) board = [None]*8 for i in range(8): board[i] = [0]*8 for i in range(64): s = path[i].getId() r, c = nodeIdToPos(s) board[r][c] = i for r in range(8): for c in range(8): print str(board[r][c]).rjust(2), print