我有一个像这样的矩阵:
http://i.imgur.com/3HiEBm4.png
您可以像这样加载:
matrix = structure(c("-", "-", "C", "G", "C", "A", "-", "0", "V", "V",
"V", "V", "C", "H", "D", "V", "DV", "V", "A", "H", "H", "D",
"DV", "D", "C", "H", "DH", "DH", "D", "V", "G", "H", "H", "D",
"H", "D", "T", "H", "H", "H", "DH", "DH", "A", "H", "H", "H",
"DH", "D", "T", "H", "H", "H", "DH", "H"), .Dim = c(6L, 9L))
从右下角开始,目标是遵循指示(D =对角线向0移动,H =向左移动,V =向上移动),以便所有路径都达到零。如您所见,有些细胞有多个方向(例如DH)。
我试图通过这样的矩阵找到所有可能的路径。我用递归做了。但我很难正确存储路径。看起来当函数返回到旧单元格以取向另一个方向时,它会将路径附加到错误的列表。
这是我的递归函数代码:
threading = function(matrix,i,j,list) { #Function wants the matrix to be threaded, number of rows and cols, and an empty list
if (matrix[i,j] == 0) { #If the recursion has arrived at zero, stop and print out the path that arrived there
print(list)
}
else { #If still elsewhere inside the matrix...
for (move in strsplit(matrix[i,j],"")[[1]]) { #Iterate through each move in that cell
if (move == "D") { #If a move is D...
list = paste(list, "D", sep="") #Append that to the path
threading(matrix,i-1,j-1,list) #Send the function to the diagonal cell
}
if (move == "V") { #If a move is V...
list = paste(list, "V", sep="") #Append that to the path
threading(matrix,i-1,j,list) #Send the function to the above cell
}
if (move == "H") { #If a move is H...
list = paste(list, "H", sep="") #Append that to the path
threading(matrix,i,j-1,list) #Send the function to the left cell
}
}
}
}
所以当我使用上面的矩阵运行它时,它会将其作为输出:
> threading(matrix, 6,9, emptylist)
[1] "HDDDDHH"
[1] "HDDDDHHD"
[1] "HDDHHDDD"
踢球者是第二个两条路径的第二个字符是错误的,但其他一切都是正确的。我该如何避免?我无法弄清楚如何正确存储路径,而不会回到原来的路径。我认为它与附加的排序和将函数发送到下一个单元格有关,但如果我反转它们,那么附加的东西永远不会发生......
答案 0 :(得分:1)
问题在于:
list = paste(list, "*", sep="")
当您点击有两个选项的单元格时,例如“VH”,for
循环将经历两次迭代:第一次迭代修改list
,然后将修改后的值传递给第二次迭代。相反,每次迭代必须使用原始值。所以你可以替换为:
l = paste(list, "*", sep="")
并将l
而不是list
传递给threading
来电。
另外,最好避免命名变量matrix
或list
,因为它们也是函数的名称。