Solved LeetCode program · 37 of 1,000
#0037 · Sudoku Solver
Original English source
Keep a shared board holding 5, 3, 0, 0, 7, 0, 0, 0, 0, 6, 0, 0, 1, 9, 5, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 6, 0, 8, 0, 0, 0, 6, 0, 0, 0, 3, 4, 0, 0, 8, 0, 3, 0, 0, 1, 7, 0, 0, 0, 2, 0, 0, 0, 6, 0, 6, 0, 0, 0, 0, 2, 8, 0, 0, 0, 0, 4, 1, 9, 0, 0, 5, 0, 0, 0, 0, 8, 0, 0, 7, and 9.
Keep a shared solved of 0. Keep a shared row safe as 0. Keep a shared column safe as 0. Keep a shared box safe as 0.
To check row at row (a whole number) with value (a whole number). Set row safe to 1.
For every column from 0 to 8.
If item (row times 9 plus column) of board is value, set row safe to 0, break.
To check column at column (a whole number) with value (a whole number). Set column safe to 1.
For every row from 0 to 8.
If item (row times 9 plus column) of board is value, set column safe to 0, break.
To check box at box (a whole number) with value (a whole number). Set box safe to 1. The startrow is (box divided by 3) times 3. The startcolumn is (box modulo 3) times 3.
For every inner row from 0 to 2.
For every inner column from 0 to 2.
The row is startrow plus inner row. The column is startcolumn plus inner column. If item (row times 9 plus column) of board is value, set box safe to 0, break.
To solve from position (a whole number). If solved is 1, return. If position is 81, set solved to 1, return. If item position of board is not 0, solve from position plus 1, return. The row is position divided by 9. The column is position modulo 9. The box is (row divided by 3) times 3 plus column divided by 3.
For every step from 0 to 8.
The digit is 9 minus step. Check row at row with digit. Check column at column with digit. Check box at box with digit.
If row safe is 1 and column safe is 1 and box safe is 1.
Set item position of board to digit. Solve from position plus 1. If solved is 1, return. Set item position of board to 0.
Solve from 0. For each value in board, display value.
Expected stdout
5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9