DFS和启发式求解八皇后问题---Python

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

import numpy as np


class eightQueens:
    def __init__(self):
        self.board = np.ones([8, 8])
        # 解的数量
        self.counter = 0
        # 当前已经放置的棋子
        self.chess_puted = []
        # 存储选中当前行每列(m,n)中棋子后的空格数
        self.colSpace = np.zeros((8, 8))

    def check_chess(self, m, n):
        if len(self.chess_puted) == 0:
            return True
        else:
            # 判断点的x y 坐标
            coordinate = np.array([m, n])
            for i in range(len(self.chess_puted)):
                # 坐标之差
                diff = coordinate - self.chess_puted[i]
                # 行、列、对角线
                if diff[0] != diff[1] and diff[0] != -diff[1] and diff[
                        0] != 0 and diff[1] != 0:
                    continue
                else:
                    return False
        return True

    def dfs(self, m):
        if m == 8:
            # 解的数量
            self.counter += 1
            print("第" + str(self.counter) + "个解的棋盘结果")
            print(self.board)
            return
        for n in range(8):
            # 检查当前位置(m,n)能否放置棋子
            if self.check_chess(m, n):
                self.board[m, n] = 0
                # 添加棋子坐标到chess_puted
                self.chess_puted.append([m, n])
                # 递归
                self.dfs(m + 1)
                # 恢复到之前的状态
                self.board[m, n] = 1
                self.chess_puted.remove([m, n])


    def findSpace(self, m, n):
        count = 0
        row, col = m, n
        # 副对角线
        while row < 8 and -1 < col:
            row += 1
            col -= 1
            count += 1
        row, col = m, n
        # 正对角线
        while row < 8 and col < 8:
            row += 1
            col += 1
            count += 1
        return 64 - count

    def evaluationFun(self, m):
        if m == 8:
            print("启发式求解:")
            self.counter += 1
            print("第" + str(self.counter) + "个解的棋盘结果")
            print(self.board)
            return

        for n in range(8):
            if self.check_chess(m, n):
                self.colSpace[m, n] = self.findSpace(m, n)
        while self.colSpace.sum(axis=1)[m] != 0:
            x, y = m, np.argmax(self.colSpace, axis=1)[m]
            self.board[x, y] = 0
            self.chess_puted.append([x, y])
            self.evaluationFun(x + 1)
            self.board[x, y] = 1
            self.colSpace[x][y] = 0
            self.chess_puted.remove([x, y])


if __name__ == '__main__':
    e = eightQueens()
    e.dfs(0)

 

你可能感兴趣的:(python,python,深度优先,启发式)