r"""Problem:The n queens problem is: placing N queens on a N * N chess board such that no queencan attack any other queens placed on that chess board. This means that one queencannot have any other queen on its horizontal, vertical and diagonal lines.Solution:To solve this problem we will use simple math. First we know the queen can move in allthe possible ways, we can simplify it in this: vertical, horizontal, diagonal left anddiagonal right.We can visualize it like this:left diagonal = \right diagonal = /On a chessboard vertical movement could be the rows and horizontal movement could bethe columns.In programming we can use an array, and in this array each index could be the rows andeach value in the array could be the column. For example:. Q . . We have this chessboard with one queen in each column and each queen. . . Q can't attack to each other.Q . . . The array for this example would look like this: [1, 3, 0, 2]. . Q .So if we use an array and we verify that each value in the array is different to eachother we know that at least the queens can't attack each other in horizontal andvertical.At this point we have it halfway completed and we will treat the chessboard as aCartesian plane. Hereinafter we are going to remember basic math, so in the school welearned this formula:Slope of a line:y2 - y1m = ----------x2 - x1This formula allow us to get the slope. For the angles 45o (right diagonal) and 135o(left diagonal) this formula gives us m = 1, and m = -1 respectively.See::https://www.enotes.com/homework-help/write-equation-line-that-hits-origin-45-degree-1474860Then we have this other formula:Slope intercept:y = mx + bb is where the line crosses the Y axis (to get more information see:https://www.mathsisfun.com/y_intercept.html), if we change the formula to solve for bwe would have:y - mx = bAnd since we already have the m values for the angles 45o and 135o, this formula wouldlook like this:45o: y - (1)x = b45o: y - x = b135o: y - (-1)x = b135o: y + x = by = rowx = columnApplying these two formulas we can check if a queen in some position is being attackedfor another one or vice versa."""from __future__ import annotationsdef depth_first_search(possible_board: list[int],diagonal_right_collisions: list[int],diagonal_left_collisions: list[int],boards: list[list[str]],n: int,) -> None:""">>> boards = []>>> depth_first_search([], [], [], boards, 4)>>> for board in boards:... print(board)['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . ']"""# Get next row in the current board (possible_board) to fill it with a queenrow = len(possible_board)# If row is equal to the size of the board it means there are a queen in each row in# the current board (possible_board)if row == n:# We convert the variable possible_board that looks like this: [1, 3, 0, 2] to# this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board])return# We iterate each column in the row to find all possible results in each rowfor col in range(n):# We apply that we learned previously. First we check that in the current board# (possible_board) there are not other same value because if there is it means# that there are a collision in vertical. Then we apply the two formulas we# learned before:## 45o: y - x = b or 45: row - col = b# 135o: y + x = b or row + col = b.## And we verify if the results of this two formulas not exist in their variables# respectively. (diagonal_right_collisions, diagonal_left_collisions)## If any or these are True it means there is a collision so we continue to the# next value in the for loop.if (col in possible_boardor row - col in diagonal_right_collisionsor row + col in diagonal_left_collisions):continue# If it is False we call dfs function again and we update the inputsdepth_first_search([*possible_board, col],[*diagonal_right_collisions, row - col],[*diagonal_left_collisions, row + col],boards,n,)def n_queens_solution(n: int) -> None:boards: list[list[str]] = []depth_first_search([], [], [], boards, n)# Print all the boardsfor board in boards:for column in board:print(column)print("")print(len(boards), "solutions were found.")if __name__ == "__main__":import doctestdoctest.testmod()n_queens_solution(4)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。