#' Distance
#'
#' Calculate the distance for any cell from the bottom left cell
#'
#' @param maze a maze object
#' @param start starting point
#'
#' @return returns a matrix with numbers as distances
#' @export
#'
#' @examples
#' maze <- makeMazeRecursiveBacktracker()
#' distance(maze)
distance <- function(maze, start = NULL){
w <- attributes(maze)$width
h <- attributes(maze)$height
if(is.null(start)){start <- attributes(maze)$start}
# Initialize distance matrix
dist_mat <- matrix(0, nrow = h, ncol = w)
row_nr <- coord_from_list_nr(start, w, h)[1]
col_nr <- coord_from_list_nr(start, w, h)[2]
# For now the starting point is fixed with 1
dist_mat[row_nr, col_nr] <- 1
# Initialize distance with 1
k <- 1
# Bruteforce search
while(any(dist_mat == 0)){
ind <- which(dist_mat == k, arr.ind = TRUE)
for(i in 1:nrow(ind)){
# ??
nr <- list_nr(ind[i,2], h + 1 -ind[i,1], width = w)
# 1N, 2E, 3S, 4W
if(maze[nr, 1] == 0 && dist_mat[ind[i,1] - 1, ind[i,2]] == 0)
dist_mat[h + 1 - maze[nr, "y"] - 1, maze[nr, "x"] + 0] <- k + 1
if(maze[nr, 2] == 0 && dist_mat[ind[i,1], ind[i,2] + 1] == 0)
dist_mat[h + 1 - maze[nr, "y"] + 0, maze[nr, "x"] + 1] <- k + 1
if(maze[nr, 3] == 0 && dist_mat[ind[i,1] + 1, ind[i,2]] == 0)
dist_mat[h + 1 - maze[nr, "y"] + 1, maze[nr, "x"] + 0] <- k + 1
if(maze[nr, 4] == 0 && dist_mat[ind[i,1], ind[i,2] - 1] == 0)
dist_mat[h + 1 - maze[nr, "y"] + 0, maze[nr, "x"] - 1] <- k + 1
}
k <- k + 1
}
return(structure(dist_mat, class = "distance", width = w, height = h, start = start))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.