Presentation is loading. Please wait.

Presentation is loading. Please wait.

The N-queens problem Team: 404 brain not found

Similar presentations


Presentation on theme: "The N-queens problem Team: 404 brain not found"β€” Presentation transcript:

1 The N-queens problem Team: 404 brain not found
Amanda Wilder, Lukas Paradiso, & Evan Holmberg

2 Abstract The project analyzes three different algorithms to find the best and time sensitive solution to the N-Queens problem. Computational complexity is considered to find the most efficient algorithm. The branch and bound, backtracking, and genetic algorithms will be compared using the time taken to place all queens on the chessboard at different values of N. Thus, we use the same amount of queens for each algorithm at runtime and then increase the amount of queens with each test. We then record the time it takes to find a solution. We sought to identify which algorithm produced the fastest execution time to find a solution based off the same number of queens for each run. The number of queens ranges from 4 to 100 and chessboards of the same sizes were used to run tests.

3 introduction In the game of chess, a queen can move as far as she pleases in any horizontal, vertical, or diagonal direction. The N-Queens Problem is the problem of placing N number of queens on a chessboard with N rows and N columns so no two queens hit each other in a single move. For no two queen to hit each other they cannot be placed on the same row, column, or diagonal and thus is a requirement for any solution. The algorithms take n as input and compute the number of ways n queens can be placed on an n x n chessboard, while finding the best solution and recording the time taken to find the solutions.

4 Formal problem statement
Check that two queens are not on the same column. Check that two queens are not on the same row. Check if more than one queen is on the same diagonals in opposing directions. Given sets 𝑆 1 , 𝑆 2 , … , 𝑆 𝑛 of values X with π‘š 1 , π‘š 2 , … , π‘š 𝑛 values in the sets. We are trying to find a solution vector X = ( π‘₯ 1 , π‘₯ 2 , … , π‘₯ 𝑛 ) chosen from the sets out of π‘š 1 , π‘š 2 , … , π‘š 𝑛 possible candidates that will satisfy the constraints in a criterion function F(X). Let X represent a chessboard of size N x N. Let π‘₯ 𝑖,𝑗 represent a square on the board at the 𝑖 π‘‘β„Ž row and the 𝑗 π‘‘β„Ž column. 𝑖, 𝑗 ∈ π‘ π‘žπ‘’π‘Žπ‘Ÿπ‘’π‘  π‘₯ 𝑖𝑗 =𝑁 Sets the number of queens to n and ensures all are placed on the chessboard.

5 Experimental procedure

6 Algorithms Backtracking Branch and Bound Genetic Algorithm

7 Backtracking Background Complexity
Used when the solver can't assign a value to the next variable or it finds a solution. In either case, the solver backtracks to a previous stage and changes the value of the variable at that stage to a value that hasn't already been tried. In the N-queens example, this means moving a queen to a new square on the current column. Time Complexity: O(n!) through reduction of calculations since various methods of nested loops each take O(N) time.

8 Backtracking: Implementation
This algorithm begins by placing queens one by one in every column, starting from the leftmost column. When a queen is placed in a column, it checks for conflicts with already placed queens. In the current column, if a row is found for which there is no conflict, it marks this row and column as part of the solution. If a row cannot be found due to conflicts, then it backtracks to another column and searches for another legal place to put the queen.

9 Backtracking code Explained
1) Start in the leftmost column 2) If all queens are placed, return true 3) Try all rows in the current column. For every tried row do: a) If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution. b) If placing queen in [row, column] leads to a solution then return true. c) If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack) and go to step (a) to try other rows. 4) If all rows have been tried and nothing worked, return false to trigger backtracking. Our code goes through all possible arrangements of queens, i.e. row/column to place them, and prints them out in the form of points on the chessboard. For example, (1,3) would indicate a queen is placed on the second row (considering we start from 0,1,2…etc.) and 3rd column. Place the first queenΒ in the left upper corner of the table. Save the attacked positions. Move to the next queen (which can only be placed to the next line). Search for a valid position. If there is one go to step 8. There is not a valid position for the queen. Delete it (the x coordinate is 0). Move to the previous queen. Go to step 4. Place it to the first valid position. If the queen processed is the last stop otherwiseΒ go to step 3. The algorithm presented cannot be turned immediately in a structured program. But the only thing needed to do so is the addition of an infinite loop that includes steps 3 to 10Β and can only be stopped by step 10.

10 The above figure shows the exact stack trace of how the backtracking program solves, for example, the 4 x 4 chessboard to get the 2 possible solutions. The numbers shown indicate the flow of control (helped us map the values in each square). Indicates when a function returns to a previous step, i.e. the algorithm backtracks. Here the function returns from 12 to 13. The algorithm backtracks from 2 to 3 to 4 as no further expansion of 2 gives any valid solutions, the algorithm backtracks.

11 Backtracking Evidence From Algorithm
As shown in the graph, our backtracking algorithm becomes inefficient around queens and takes an incomputable time to find a solution.

12 Branch and bound The goal of a B&B algorithm is to find a value x that maximizes or minimizes the value of a real-valued function f(X), among some set S of valid, or possible solutions. It recursively splits the search space into smaller spaces, i.e. branching, then minimizes f(X) on these smaller spaces. To improve on the performance of backtracking, it keeps track of bounds on the minimum that it is trying to find, and uses these bounds to "prune" the search space, eliminating candidate solutions that it can prove will not contain an optimal solution. O(n!) An enhancement of backtracking Β For each node (partial solution) of a state-space tree, computes a bound on the value of the objective function for all descendants of the node (extensions of the partial solution) Β Uses the bound for: – ruling out certain nodes as β€œnonpromising” to prune the tree – if a node’s bound is not better than the best solution seen so far – guiding the search through state-space

13 Branch and bound: Implementation
We chose to keep Boolean arrays that tell us which rows and which diagonals are occupied. Pre-processing: Create two N x N matrix one for / diagonal and other one for \ diagonal (slashCode and backslashCode). They are filled so that two queens sharing a same /Β­diagonal will have the same value in matrix slashCode, and if they share same \ Β­diagonal, they will have the same value in backslashCode matrix. For an N x N matrix, we fill slashCode and backslashCode matrix using: slashCode[row][col] = row + col backslashCode[row][col] = row – col + (N-1) >>> N – 1 used to ensure code is never negative because it must be used in array Before queen i is placed on row j, we check whether row j is used (an array holds row data). Then we check whether slash code ( j + i ) or backslash code ( j – i + 7 ) are used (two arrays tell which diagonals are occupied). If yes, then we try a different location for queen i. If not, then we mark the row and the two diagonals as used and do a recursive call on queen i + 1. After the recursive call returns and before we try another position for queen i, we reset the row, slash code and backslash code as unused again.

14

15 Branch and bound Evidence From Algorithm
As shown in the graph, our B & B algorithm becomes inefficient around 40 queens, which is a slight improvement to Backtracking. Then it takes exponentially longer to find a solution.

16 Genetic Algorithm Genetic Algorithm is an optimization algorithm, which is based on natural selection and the ideas of evolution. Its goal is to find the optimal solution, but it is not guaranteed because of its randomness. A population of chromosomes is selected randomly. Chromosomes can be altered by mutation and crossover. These chromosomes are then evaluated and fixed towards better solutions. Genetic Algorithm gives the optimal solution depending on the nature of the fitness function, the fitness function determines which chromosomes (solutions) are copied to the final solution. O(nlogn) based on calculation of methods in the algorithm.

17 Genetic Algorithm: Implementation
Explains steps of the implemented code to calculate which chromosomes are chosen, fitness ratings calculated, and solution found. A random population of Queens is initiated (Parent pool) Calculate each solutions fitness rating. The possible solutions are given a fitness rating which is based on the number of collisions on the board e.g. A fitness rating of 0 would be a solution Select better solutions based on their fitness values and reject others The candidates with the lower fitness ratings then are to be used as parents If the most suitable solutions are found or maximum number completed, stop. Else, do a crossover operation to create a new generation of candidate solutions, the offspring (Child pool) and replace duplicates with unused chromosomes Copy Child pool to Parent pool and find best fitness’ solutions of new Parent pool. Compare fitness’ of both Parent pools and the better chromosome (solution) is copied to the zeroth location of the new Parent pool. Steps 2-6 are repeated until a solution is found. Chromosomes = solutions

18 Representation of how our algorithm works with fitness functionand crossover to find a solution.
In (a), we have an initial population of 4 individuals. They are scored by the fitness function in (b); the top individual scores a 24 and the bottom an 11. It works out that the top individual has a 31% chance of being chosen on each selection. In (c), selection has given us two pairs of mates, and the cross-over points have been chosen. One individual mates twice; one not at all. In (d), we see the new offspring, generated by cross-over of their parentsβ€˜ genes. In (e), mutation has changed the two bits surrounded by boxes. This gives us the population for the next generation.

19 Genetic Algorithm Evidence From Algorithm

20 Interpretation Original hypothesis:
As the number of queens is increased: Backtracking will take the longest to find a solution. Branch and Bound will optimize that of backtracking and produce a much faster result with a larger amount of data. A genetic algorithm we believe will produce the fastest solution .

21 - # of Queens Backtracking Branch & Bound Genetic Algorithm 4 0.009921
8 10 20 0.4889 0.1717 30 232.1 11.31 31 305.3 13.87 32 396.8 94.78 33 - 155.2 35 228.9 40 50 77.914 60 70 119.78 80 143.32 90 170.12 100 199.12

22 As we can see, the Backtracking and B & B algorithms stop around 35 queens because it takes so long to run. The Genetic Algorithm runs slower at smaller values of N, such as N=4 and 8, but becomes the faster algorithm with larger values of N

23 Interpretation cont. The Genetic Algorithm gives faster solutions as it works on a population of chromosomes, i.e. solutions, and processes them to get the result. Thus, it explores the search space, which helps to get the solution close to the global optima (a solution better than all others). But because it is a random search and optimization algorithm, it does not guarantee an optimal solution. The Backtracking Algorithm can eliminate large sets of solutions without going through every element in the set (enumeration), but Branch and Bound Algorithm is still an improvement on Backtracking. B&B will take less time than Backtracking Algorithm to solve N Queens Problem because it rules out nonpromising positions. These two algorithms cannot provide solutions in ample time when N values are high. Therefore, these two algorithms are not efficient and effective to solve N Queens Problem; whereas, Genetic Algorithm can provide accurate solutions to higher valued Queens.

24 Conclusion The Genetic Algorithm has a better execution time and number of improvements over the other two algorithms; i.e., Backtracking and Branch and Bound. Therefore, it can be concluded that, the Genetic Algorithm is much better w.r.t run time with larger N values.

25 Future work Work on this project can be extended by adding a few algorithms like Dynamic Programming, Greedy, and Hill Climbing to solve the N-Queens Problem. Making a comparative study of additional algorithms would make the whole problem analysis more effective by providing us with data to more accurately conclude which algorithm is most efficient. We could modify each of the three algorithms to work with even larger values of N for more data.

26 Questions What are the differences between backtracking and branch and bound? Backtracking iterates through all positions and backtracks when it hits a dead end. B & B knows it will hit a dead end because of a partial solution and stops exploring a branch, making it the faster algorithm. Do one or more algorithms become incomputable after a certain number of queens? If so, which one(s). Backtracking becomes inefficient before Branch and Bound, but both algorithms take too long to find a solution after a certain number of queens. Does the Genetic Algorithm ever run slower than the other algorithms? Yes, this algorithm is slower to find a solution at values of N less than or equal to 20. Is the N-Queens Problem a constraint satisfaction or optimization problem? Constraint Satisfaction Problem Which algorithm works best with larger values of N? Genetic Algorithm


Download ppt "The N-queens problem Team: 404 brain not found"

Similar presentations


Ads by Google