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("end\n\n")
        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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值