Valid Sodoku Problem

Solving the Valid Sodoku LeetCode Problem using r

Given a matrix determine if it’s a valid Sodoku board. Based on the following rules

  • Each row must contain the digits 1-9 without repeating
  • Each column must contain the digits 1-9 without repeating
  • Each 3×3 sub-box must contain the digits without repeating

To use as our test case we will have two Sodoku boards, 1 that is valid and 1 that is not.

Board_true <- matrix(c(
"5","3",".",".","7",".",".",".",".",
"6",".",".","1","9","5",".",".",".",
".","9","8",".",".",".",".","6",".",
"8",".",".",".","6",".",".",".","3",
"4",".",".","8",".","3",".",".","1",
"7",".",".",".","2",".",".",".","6",
".","6",".",".",".",".","2","8",".",
".",".",".","4","1","9",".",".","5",
".",".",".",".","8",".",".","7", "9"),
nrow = 9,
ncol = 9,
byrow = T
)

Board_false <- matrix(c(
"8","3",".",".","7",".",".",".",".",
"6",".",".","1","9","5",".",".",".",
".","9","8",".",".",".",".","6",".",
"8",".",".",".","6",".",".",".","3",
"4",".",".","8",".","3",".",".","1",
"7",".",".",".","2",".",".",".","6",
".","6",".",".",".",".","2","8",".",
".",".",".","4","1","9",".",".","5",
".",".",".",".","8",".",".","7", "9"),
nrow = 9,
ncol = 9,
byrow = T
)
Valid_Sodoku <- function(Board){
# Sub "." for NA

Board <- gsub("[.]", NA, Board)


ErrorChk <- list(RowCheck=list(),
                 ColCheck = list(),
                 SqCheck = list())
for(i in 1:9){
ErrorChk$RowCheck[i] <- all(table(Board[i,])==1)
ErrorChk$ColCheck[i] <- all(table(Board[,i])==1)
}
#  Squares

Sq1 <- all(table(Board[1:3, 1:3])==1)
Sq2 <- all(table(Board[1:3, 4:6])==1)
Sq3 <- all(table(Board[1:3, 7:9])==1)

Sq4 <- all(table(Board[4:6, 1:3])==1)
Sq5 <- all(table(Board[4:6, 4:6])==1)
Sq6 <- all(table(Board[4:6, 7:9])==1)

Sq7 <- all(table(Board[7:9, 1:3])==1)
Sq8 <- all(table(Board[7:9, 4:6])==1)
Sq9 <- all(table(Board[7:9, 7:9])==1)
 
ErrorChk$SqCheck <- data.frame(Sq1, Sq2,Sq3,Sq4,Sq5,Sq6,Sq7,Sq8,Sq9)

errors <- names(unlist(ErrorChk))[which(unlist(ErrorChk) == F)]
for(i in 1:length(errors)){
  cat(paste0("Error: ", errors[i], " \n"))
 }
}
> Valid_Sodoku(Board = Board_true)
Error: NA 
Error:  
> Valid_Sodoku(Board = Board_false)
Error: ColCheck1 
Error: SqCheck.Sq1 

Board_false fails the valid check because both the first column and first 3×3 sub-grid have duplicate 8s.

Leave a Reply

Your email address will not be published. Required fields are marked *