I want to solve a maze in R. I created a function inspired by corresponding Python code:
You could always add collectors so you could see how many times it cycled and how many steps to each solution were needed.
This uses an external list. Here is the updated search
function. there is one new line where if == 2
.
search = function(maze, x, y, directions = NULL){
if(!exists("directions")) {
directions <- list()
}
directions <- append(directions, c(x, y))
if (x == 0 | y == 0) { # outside of matrix limits
return(FALSE)
} else if (x > nrow(maze) | y > ncol(maze)) { # outside of matrix limits
return(FALSE)
} else if (maze[x, y] == 2){
print(paste('I am in point', x, y))
colorPrint(maze) # print with 3's colored
directedPrint(maze, directions) # print solution with arrows
d[[length(d) 1]] <<- length(directions) # how many directions were taken?
return(TRUE)
} else if (maze[x, y] == 1){
print(paste('wall in point', x, y))
return(FALSE)
} else if (maze[x, y] == 3){
print(paste('visited point', x, y))
return(FALSE)
}
#set as marked
print(paste('visited point', x, y))
maze[x, y] <- 3 # annotate path of travel
if((x < nrow(maze) & search(maze, x 1, y, directions))
| (y > 1 & search(maze, x, y - 1, directions))
| (x > 1 & search(maze, x - 1, y, directions))
| (y < ncol(maze) & search(maze, x, y 1, directions))) {
return(TRUE)
}
return(FALSE)
}
To use this one, you'll need to create a list in the global environment.
d = list()
dt2 <- matrix(data = c(rep(0, 5), 1,
1, 1, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 0, 2,
rep(0, 5), 1),
nrow = 6, ncol = 6, byrow = F)
search(dt2, 1, 1)
This returned 43 solutions, where the shortest sequence was 20 steps & the longest was 48.