八皇后问题所有可能算法-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

上表格为我的思路

主要遇到的问题:

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

你可能感兴趣的:(算法)