Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.’.
You may assume that there will be only one unique solution.
Solution
- for each tuple that’s not a number already, try 1-9 numbers
- if the board is still valid after placing the number, place it for now
- continue to solve board, only if all number placed are valid can we return true
- if we reached unvalid board, redo by setting the numbers to ‘.’
|
|
N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
|
|
Solution
Very interesting problem: The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally. So easily we come to the conclusion that each row can only stand 1 queen, as well as each column, diagonal.
Because of the previous observation, we can use a 1D array to store the positions, instead of using 2D array.
ColforRow[i] records the queen in row i is in which columnFor each row, try all columns and if is valid, check for next row
When row == n, all rows have found their queens, these are valid solutions
What are valid positions for current row? Only need to check column and diagonal
|
|
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Solution
- Add count when a new solution is found (row==n)
|
|