Last active
January 4, 2016 18:49
-
-
Save sqeezy/8663609 to your computer and use it in GitHub Desktop.
Simple solution for knight tour problem. Slow with n>5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
movements = [[1, 2], [1, -2], [-1, -2], [-1, 2], [2, 1], [-2, 1], [2, -1], [-2, -1]] | |
field = [] | |
results = [] | |
def start(n=5, m=5, xStart=2, yStart=2): | |
moves = [] | |
for i in range(0, n): | |
field.append([]) | |
for j in range(0, m): | |
field[i].append(0) | |
moves.append([xStart, yStart]) | |
field[xStart][yStart] = 1 | |
jump(moves) | |
#print len(results) | |
#for k in range(0,15): | |
# print results[k] | |
def jump(moves): | |
if len(moves) == len(field) * len(field[0]): | |
#speichere Ergebnis | |
results.append(copy.copy(moves)) | |
printMatrix(moves) | |
return | |
nextP = next_positions(moves[-1][0], moves[-1][1]) | |
if len(nextP) == 0: | |
#abbruch | |
return | |
for n in nextP: | |
field[n[0]][n[1]] = 1 | |
moves.append(n) | |
jump(moves) | |
moves.pop() | |
field[n[0]][n[1]] = 0 | |
def next_positions(x, y): | |
result = [] | |
for move in movements: | |
newX = x + move[0] | |
newY = y + move[1] | |
if (xInRange(newX) and yInRange(newY) ): | |
if field[newX][newY] == 0: | |
result.append([newX, newY]) | |
return result | |
def xInRange(x): | |
return (0 <= x <= len(field) - 1) | |
def yInRange(y): | |
return (0 <= y <= len(field[0]) - 1) | |
def printMatrix(moves): | |
for position in moves: | |
for x in range(0,len(field)): | |
lineContent = "| " | |
for y in range(0,len(field[0])): | |
if(x == position[0] and y == position[1]): | |
lineContent+="K " | |
else: | |
lineContent+="o " | |
lineContent+="|" | |
print(lineContent) | |
print("") | |
if __name__ == "__main__": | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment