python八皇后问题递归算法_八皇后问题所有可能算法-python

最近复习了一下算法,太久没有碰脑子都生锈了。python容易调先上python的代码,往后有时间再上Java的。

# -*- coding: utf-8 -*-

import copy;

__author__ = 'jinyao.xian';

total = 0;

class Position:

def __init__(self, x, y):

self.x = x;

self.y = y;

def eight_queen(num):

blank_chess_board = [[0 for _ in range(num)] for _ in range(num)];

def queen(chess_board, nextx, chess_num=0):

if chess_num == num: # 可使用nextx作为递归最终条件 nextx == num

print_board(chess_board);

else:

for y in range(len(chess_board[nextx])): # 纵向遍历

if can_use_this_position(Position(nextx, y), chess_board):

new_chess_board = copy.deepcopy(chess_board);

put_chess(Position(nextx, y), new_chess_board);

queen(new_chess_board, nextx + 1, chess_num+1); # 横向遍历

queen(blank_chess_board, 0);

def print_board(chess_board):

global total;

total += 1;

for x in chess_board:

print(x);

print("")

def can_use_this_position(position, chess_board):

if 1 in chess_board[position.x]:

return False;

for x in range(len(chess_board)):

if 1 == chess_board[x][position.y]:

return False;

tmp = abs(x - position.x);

if position.y - tmp >= 0 and chess_board[x][position.y - tmp] == 1:

return False;

elif position.y + tmp < len(chess_board[x]) and chess_board[x][position.y + tmp] == 1:

return False;

return True;

def put_chess(position, chess_board):

chess_board[position.x][position.y] = 1;

return chess_board;

if __name__ == '__main__':

eight_queen(8);

print(total);

y7

y6

y5

y4

y3

y2

y1

y0

x0

x1

x2

x3

x4

x5

x6

x7

上表格为我的思路

主要遇到的问题:

棋盘没有副本,所以用了个深度拷贝来维持剩下棋子所对应的棋盘

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值