New 8 queens question with search algorithm by python

New 8 queens question with search algorithm by python,第1张

New 8 queens question with search algorithm by python

The state: 

-1 indicates that the position in the board is vacant, meanwhile 0 represents a position in a card that has been prevented from being queen.

Predictive movement analysis

x_move = [2, 1, -1, -2, -2, -1, 1, 2]
y_move = [1, 2, 2, 1, -1, -2, -2, -1]

First, determining the size of the provided board; then make sure that each Queen in borad meets the requirements given in the title; call the provided module function to implement the search algorithm.

This is how to make the goal:

def goal_test_func(state):
    temp_state = copy.deepcopy(state)
    temp_state = np.array(temp_state)
    positions = []
    for i in range(0, M):
        for j in range(0, N):
            if temp_state[i][j] == 1 or temp_state[i][j] == 0:
                positions.append((i, j))
    for (i, j) in positions:
        temp_state[i, :] = 1
        temp_state[:, j] = 1
        for k in range(0, N):
            row1 = i - abs(j - k)
            row2 = i + abs(j - k)
            if 0 <= row1 < M:
                temp_state[row1][k] = 1
            if 0 <= row2 < M:
                temp_state[row2][k] = 1
    if temp_state.sum() == M*N:
        # 存储结果
        f = open('tester_outcome.txt', 'a+')
        for (i, j) in positions:
            f.write("(" + str(i) + ", " + str(j) + ")->")
        f.write("endnn")
        f.close
        return True
    return False

After all, use "print_action_list" and "action_string" functions to show the result:
 

def print_action_list( act_list ):
     print( ", ".join([action_string(action) for action in act_list]) )

def action_string( action ):
          return str(action)

make_qc_problem(m=3, n=10)
problem_info_func()

for i in range(M):
	actions = poss_act_func(initial_state)
	state = successor_func(actions[0], initial_state)
	result = goal_test_func(state)
	print_action_list(actions)
	print(state)

Let's see the result(show the action firstly, then show the result one by one):

Board Shape: rows=3, columns=10

(0, 0)
[[0, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]]
(2, 1), (1, 2)
[[1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, 0, -1, -1, -1, -1, -1, -1, -1, -1]]
(2, 1), (1, 2)
[[1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, 0, -1, -1, -1, -1, -1, -1, -1, -1]]
[Finished in 296ms]

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5680123.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存