Suppose I have the following sudoku:
problem <- matrix(c(
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 ,9
), nrow = 9)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 5 6 0 8 4 7 0 0 0
[2,] 3 0 9 0 0 0 6 0 0
[3,] 0 0 8 0 0 0 0 0 0
[4,] 0 1 0 0 8 0 0 4 0
[5,] 7 9 0 6 0 2 0 1 8
[6,] 0 5 0 0 3 0 0 9 0
[7,] 0 0 0 0 0 0 2 0 0
[8,] 0 0 6 0 0 0 8 0 7
[9,] 0 0 0 3 1 6 0 5 9
I am trying to manually write a procedure (e.g. backtracking) to solve this sudoku.
Currently, I thought of the two following ideas that could be useful:
1) For a given row or a given column - what numbers are valid choices?
The following code looks at what possible numbers are valid choices in the first column:
y = 1:9
setdiff(y, problem[1,])
[1] 1 2 3 9
2) At any point, does a given row or column result in a violation? (i.e. same number more than once - excluding 0)
#TRUE = no violation, FALSE = violation
check_vector <- function(v) {
for (i in 1:9) {
if (sum(v == i) > 1) {
return(FALSE)
}
}
return(TRUE)
}
# no violation
v1 = c(5, 3, 0, 0, 7, 0, 0, 0, 0)
# violation (3,3)
v2 = c(5, 3, 3, 0, 7, 0, 0, 0, 0)
> check_vector(v1)
[1] TRUE
> check_vector(v2)
[1] FALSE
My Question: I am not sure how I can use these functions together to backtrack through the sudoku and fill out all numbers. Can someone please show me how to do this?
Thanks!
Note: If possible, I would like the final answer to use the code I already wrote
sudoku::solveSudoku(problem)
– Remscheidcheck_vector
is just a tiny part in a sudoku solver, and there is still a long way to go with it if you request others to use it anyway before finishing the solver, since you don't have your own roadmap for the solver so far. Also, the sudoku rules are not fully included incheck_vector
yet. – Petition