import collections
import random
class checkerboard(object):
初始化棋盤
def __init__(self, len):
self.len = len
self.position_has_gone = set()
def init_checkerboard(self):
position =
for i in range(1, self.len + 1):
line =
for j in range(1, self.len + 1):
return position
def init_hourse_position(self):
x = random.randint(1, self.len)
y = random.randint(1, self.len)
self.position_has_gone.add((x, y))
return (x, y)
def get_next_positions(self, init_position):
next_position =
x, y = init_position
if x - 1 >= 1:
if y - 2 >= 1:
if y + 2 <= self.len:
if x - 2 >= 1:
if y - 1 >= 1:
if y + 1 <= self.len:
if x + 1 <= 8:
if y - 2 >= 1:
if y + 2 <= self.len:
if x + 2 <= self.len:
if y - 1 >= 1:
if y + 1 <= self.len:
return list(set(next_position) - self.position_has_gone) # 列表
def choose_next_position(self, next_positions, no_ok_position):
貪心選擇下一步的下一步選擇方案最小的路
:param next_positions: 下一步可以選擇的位置
:param house_position: 本身的位置
:return:下一步走的位置
min_choice = 9
min_index = 0
if no_ok_position:
next_positions = list(set(next_positions) - set(no_ok_position))
if len(next_positions) == 0:
print('saaa')
return false
for index, position in enumerate(next_positions):
choice = len(self.get_next_positions(position))
if choice < min_choice:
min_choice = choice
min_index = index
self.position_has_gone.add(next_positions[min_index])
return next_positions[min_index]
len = 8
trace = # 有序字典,用於記錄每步的位置
checkerboard_obj = checkerboard(len)
checkerboard = checkerboard_obj.init_checkerboard() # 獲取棋盤所有格仔
house_position = checkerboard_obj.init_hourse_position() # 獲取馬的初始位置
# 獲取馬的下乙個可能位置
print('初始化位置', house_position)
while len(checkerboard_obj.position_has_gone) < len * len: # 當沒有走完全部格仔時,繼續走下一步直至走完
next_positions = checkerboard_obj.get_next_positions(house_position)
next_step = checkerboard_obj.choose_next_position(next_positions, no_ok_position=none)
if next_step == false:
break
else:
house_position = next_step
print(trace)
showlist =
for i in range(8):
line =
for j in range(8):
for index, item in enumerate(trace):
showlist[item[0] - 1][item[1] - 1] = index + 1
for item in showlist:
print(item)
回溯演算法(馬踏棋盤)
近期學習了回溯演算法於是自己寫了馬踏棋盤的遞迴以及非遞迴方式的 theme 馬踏棋盤 回溯演算法 coder 秒針的聲音 time 2015.1.11 include include include define m 8 typedef struct nodehorse horse horse1 i...
馬踏棋盤演算法
為.c檔案 include include include define rows 8 define cols 8 int cheesboard rows cols const int movex 8 const int movey 8 初始化棋盤,將棋盤所有的位置賦值為0 void initboa...
馬踏棋盤演算法
將馬隨機放在西洋棋的board 0 7 0 7 的某個方格中,馬按走棋規則進行移動。走遍棋盤上全部64個方格。編制非遞迴程式,求出馬的行走路線,並按求出的行走路線,將數字1,2,64依次填入乙個8 8的方陣,輸出之。利用回溯法的思想,馬的走法總共有8,c 8 b 8 c是橫座標,b是縱座標。總共有6...