Recursion

Solve Sudoku

Given a Sudoku puzzle board, solve the board by modifying it in-place. Do not return anything.

To solve the board, you must ensure that every row, column, and 3x3 section outlined in bold contains every digit 1 though 9.

Example:

board =\texttt{board =}

image

=> returns\texttt{=> returns}

image

Note that board always takes this form, where ' ' means empty:

First Test Case:

0. Problem

This problem is very similar to the N-Queens problem. In N-Queens we placed a queen row-by-row. In Sudoku we place a number square-by-square.

Our function should try every possible number 1-9 at each empty square, until it eventually reaches a complete board. The function needs to know the current board.

1. Recursion

We can easily write this recursively. Just consider adding 1-9 to the current empty square, and then repeating the process. Here's pseudocode:

2. Base case

We want the visitAll function to stop when the board is full.

3. Code

We wrote some pseudocode above, and we need to convert it to actual code.

Here's how we fill in "the next empty square":

Here's how we fill in "num can be added at row, col":

Here's how we fill in the base case:

Here's the full code:

Time Complexity O(9num_dots)O(9^\texttt{num\_dots}). For each dot, we might try 9 different choices.

Space Complexity O(993)O(9*9*3) for all the data structures we use.

Call Stack Complexity O(num_dots)O(\texttt{num\_dots}). visitAll() gets as deep as the number of dots. One call per dot.

Mark as Completed:
Submits:
solveSudoku
Test your code to get an output here!
solveSudoku(
)
Test your code to get an output here!