在特定的递归DFS R示例中采用什么图结构?

myzjeezk  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(89)

我特灵弄清楚https://www.algorithms-and-technologies.com/dfs/r中所示的递归DFS R代码片段所假设的数据结构。我最初假设它是一个邻接列表,类似于:

start <- list(
  "0" = c("1","2"),
  "1" = c("3","4"),
  "2" = c("5","6"),
  "3" = c(),
  "4" = c(),
  "5" = c(),
  "6" = c()
)

但我没办法让它工作有人能帮帮我吗

2lpgd968

2lpgd9681#

在我看来,他们似乎是在做这样的假设:

thelist <- list(value = 123,
                children = list(list(value = 456,
                                     children = list()),
                                list(value = 789,
                                     children = list())))

即,每个节点是具有value(当被搜索时,其将与target匹配)和作为相同格式的节点的子节点的列表的列表。
编辑以添加:
这段代码将您的start转换为thelist的内容:

start <- list(
  "0" = c("1","2"),
  "1" = c("3","4"),
  "2" = c("5","6"),
  "3" = c(),
  "4" = c(),
  "5" = c(),
  "6" = c()
)

toNode <- function(n) {
  result <- list(value = n)
  children <- list()
  names <- start[[n]]
  for (i in seq_along(names)) {
    cat("Processing node ", n, " child ", names[i], "\n")
    children[[i]] <- toNode(names[i])
  }
  result$children <- children
  result
}

thelist <- toNode("0")
#> Processing node  0  child  1 
#> Processing node  1  child  3 
#> Processing node  1  child  4 
#> Processing node  0  child  2 
#> Processing node  2  child  5 
#> Processing node  2  child  6

创建于2023年2月23日,使用reprex v2.0.2
你可以打印thelist的最终值,但是它很难看,下面是dput(thelist)给出的结果的重新格式化版本:

list(value = "0", children = list(
  list(value = "1", children = list(
    list(value = "3", children = list()),
    list(value = "4", children = list())
  )),
  list(value = "2", children = list(
    list(value = "5", children = list()),
    list(value = "6", children = list())
  ))
))

相关问题