[python]连线不过黑点问题尝试

0 -1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

import numpy as np

Found = False
# zx:=row number;zy:=col number
zx = 6
zy = 5
# black point(bx,by)
bx = 1
by = 0
times = 0

def generatePoints():
global zx
global zy
global bx
global by
points = np.zeros((zx,zy))
for row in range(zx):
for cal in range(zy):
p = 0
if row == by and cal == bx:
p = -1
points[row,cal] = p
return points

def walk(curPoint,keepWalking,pathMap,step):
global Found
global zx
global zy
global times
# (1,0)
nextPoint = [curPoint[0] + 1, curPoint[1]]
if pathMap[nextPoint[0],nextPoint[1]] == 0:
nestStep = step + 1
newMap = pathMap.copy()
newMap[nextPoint[0], nextPoint[1]] = nestStep
walk(nextPoint, True, newMap,nestStep)
else:
if 0 not in pathMap:
Found = True
print("solution")
print(pathMap)
else:
times += 1

# (-1,0)
nextPoint = [curPoint[0] - 1, curPoint[1]]
if pathMap[nextPoint[0],nextPoint[1]] == 0:
nestStep = step + 1
newMap = pathMap.copy()
newMap[nextPoint[0], nextPoint[1]] = nestStep
walk(nextPoint, True, newMap,nestStep)
else:
if 0 not in pathMap:
print("solution")
Found = True
print(pathMap)
else:
times += 1

# (0,1)
nextPoint = [curPoint[0], curPoint[1] + 1]
if pathMap[nextPoint[0],nextPoint[1]] == 0:
nestStep = step + 1
newMap = pathMap.copy()
newMap[nextPoint[0],nextPoint[1]] = nestStep
walk(nextPoint, True, newMap,nestStep)
else:
if 0 not in pathMap:
Found = True
print("solution")
print(pathMap)
else:
times += 1
# (0,-1)
nextPoint = [curPoint[0], curPoint[1] - 1]
if pathMap[nextPoint[0],nextPoint[1]] == 0:
nestStep = step + 1
newMap = pathMap.copy()
newMap[nextPoint[0],nextPoint[1]] = nestStep
walk(nextPoint, True, newMap,nestStep)
else:
if 0 not in pathMap:
Found = True
print("solution")
print(pathMap)
else:
times += 1

def pathing(sp,points):
step = 1
pathMap = points.copy()
pathMap[sp[0],sp[1]] = step
walk(sp,True,pathMap,step)

points = generatePoints()
print("initial points map")
print(points)
for row in range(zx):
for cal in range(zy):
p = points[row,cal]
if p == 0:
# start
sp = [row,cal]
pathing(sp,points)
else:
continue

print("no solution found")
print(times,"tried")


initial points map
[[ 0. -1. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
no solution found
1899691 tried

initial points map
[[-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.]]
solution
[[-1. 1. 18. 19. 20.]
[ 3. 2. 17. 16. 21.]
[ 4. 9. 10. 15. 22.]
[ 5. 8. 11. 14. 23.]
[ 6. 7. 12. 13. 24.]]
47524 tried
++++++++++++++++++++++++++++++
initial points map
[[ 0. -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.]]
solution
[[ 1. -1. 29. 28. 27.]
[ 2. 11. 12. 25. 26.]
[ 3. 10. 13. 24. 23.]
[ 4. 9. 14. 21. 22.]
[ 5. 8. 15. 20. 19.]
[ 6. 7. 16. 17. 18.]]
443 tried

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客