N Queens Breadth First Search

时间:2017-09-10 22:20:49

标签: python

我正在尝试使用广度优先搜索找到N皇后问题的解决方案。

现在,这个解决方案最初是针对n-rocks编写的,但我无法调整它以适应N Queens拼图。我明白我基本上都在尝试对角线正确搜索?

我尝试关注https://rosettacode.org/wiki/N-queens_problem#Python:_Raymond_Hettingers_permutations_based_solution并调整is_goal_queens,但没有成功。

我只需要找到一个解决方案,而不是所有解决方案,所以第一个被BFS击中的解决方案就是我需要的。

我还需要调整它以禁止该初始板上的字段(X,Y)。所以我假设队列从特定的行/列集开始?

import sys
import time


F = str(sys.argv[1])
# Size of board
N = int(sys.argv[2])
# Row
X = int(sys.argv[3])
# Col
Y = int(sys.argv[4])

print F, N, X, Y

initial_board = [[0] * N] * N


def q_count_on_row(board, row):
    return len(board[row])


# Count # of pieces in given column
def q_count_on_col(board, col):
    return len([row[col] for row in board])

def q_count_pieces(board):
    return len([len(row) for row in board])


# Return a string with the board rendered in a human-friendly format
def printable_board_queens(board):
    return "\n".join([" ".join(["Q" if col else "." for col in row]) for row in board])


# Add a piece to the board at the given position, and return a new board (doesn't change original)
def add_piece(board, row, col):
    return board[0:row] + [board[row][0:col] + [1, ] + board[row][col+1:]] + board[row+1:]


# Get list of successors of given board state
def successors2(board):
    return [add_piece(board, r, c) for r in range(0, N) for c in range(0, N) if count_pieces(board)+1 <= N]


# check if board is a goal state
def is_goal_queens(board):
        return q_count_pieces(board) == N and \
    all([q_count_on_row(board, r) != r-1 for r in range(0, N)]) and \
    all([q_count_on_col(board, c) != c-1 for c in range(0, N)])


def solve_queens(initial_board):
    fringe = [initial_board]
    while len(fringe) > 0:
        for s in successors2(fringe.pop(0)):
            print s
            if is_goal_queens(s):
                return s
            fringe.append(s)
    return False


def main():
    if F == 'nqueens':
        print ("Starting from initial board:\n" + printable_board_queens(initial_board) + "\n\nLooking for solution...\n")
        solution = solve_queens(initial_board)
        print (printable_board_queens(solution) if solution else "Sorry, no solution found. :(")
    else:
        print "Not a valid argument"


if __name__ == '__main__':
    start_time = time.time()
    main()
    print time.time() - start_time

编辑:

我更改了is_goal_queens(),输出的结果是:

Starting from initial board:
. . . .
. . . .
. . . .
. . . .

Looking for solution...

[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Q . . .
. . . .
. . . .
. . . .
0.0

0 个答案:

没有答案