Original link: https://justyy.com/archives/61763
Given a Sudoku, we can use a depth-first search algorithm, an iterative deepening search algorithm, or a breadth-first search algorithm to find possible solutions. Conversely, if we are to design an algorithm to generate valid Sudoku, we need to clarify the following questions:
- Must the generated Sudoku have a solvable state? Yes
- Does the generated Sudoku have multiple solutions? We can assume that the returned Suduoku has only 1 unique solution
- How difficult is the generated Sudoku? We can set a parameter for this: easy, medium or hard
There are a total of 6.671×10^21 valid Sudoku states, and this number drops to 5.4×10^9 states if we ignore repeated states such as rotations, mirroring states, etc. We could randomly generate a matrix filled with the numbers 1-9 and check if it is a valid Sudoku, but this is very inefficient because the resulting matrix most likely will not be a valid Sudoku.
Design an Algorithm for Random Sudoku
In order to design an efficient algorithm to generate a random valid Sudoku, we can use the following algorithm:
- Use a backtracking (depth-first search) algorithm to generate a valid complete Sudoku with randomness. For example, instead of trying to fill in the numbers 1 through 9 in sequence, we could choose numbers at random.
- Delete a random number each time
- Check if the Sudoku state is solvable and contains exactly one solution (using a depth-first search algorithm, also known as backtracking or breadth-first search algorithm)
- If yes, proceed to step 2, if we have not removed N numbers. The number of numbers to remove corresponds to the difficulty level. Removing more numbers makes the sudoku state harder and vice versa.
- If it is neither solvable nor has a solution, we have to put the number back and try again with another random number (step 2)
Here’s the answer from ChatGPT 3.5 (Open AI + Microsoft Azure):
- Create a 9×9 grid and fill it with numbers 1 through 9.
- Pick a number at random and delete it.
- Repeat step 2 until all numbers are removed from the grid.
- Checks if the grid is a valid sudoku.
- If the mesh is valid, it is returned as the solution.
- If the mesh is not valid, repeat steps 2-5 until a valid solution is found.
English: Teaching Kids Programming – How to Design a Random Sudoku? Algorithm to Design a Random Sudoku
There are a total of 665 Chinese characters in this article, count it right.
Algorithm Design for Random Sudoku Game (Sudoku) . ( AMP Mobile Accelerated Version )
The post Algorithm Design of Random Sudoku Game (Sudoku) first appeared on Little Laizi’s British Life and Information .
This article is transferred from: https://justyy.com/archives/61763
This site is only for collection, and the copyright belongs to the original author.