【发布时间】:2018-09-26 04:46:28
【问题描述】:
我正在尝试创建一个遍历数字字典的递归函数,然后输出每个节点的遍历路径。
数据结构如下所示:
var tree = new Dictionary<int, List<int>>()
{
{888, new List<int>() {44}},
{ 44, new List<int>() {183, 275, 100, 216}},
{100, new List<int>() {299, 400}},
{299, new List<int>() {504}},
{216, new List<int>() {33}}
};
所以表示数据结构的树形结构看起来像这样
888
/ \
44 (many other nodes and subnodes)
/ / \ \
183 275 100 216
/ \ \
299 400 33
/
504
我想返回一个输出类似这样的列表的列表
[888, 44, 183]
[888, 44, 275]
[888, 44, 100, 299, 504]
[888, 44, 100, 400]
[888, 44, 216, 33]
这是迄今为止的内容,可能不正确。我可以成功地得到一些我想要的结果。我认为问题在于它没有删除具有访问过所有子节点的子节点的节点。
public List<int[]> FindPaths(int currentNode, Dictionary<int, List<int>> tree, List<int> temp, List<int> visitedNodes)
{
if (tree.ContainsKey(currentNode))
{
if (!visitedNodes.Contains(currentNode))
{
visitedNodes.Add(currentNode);
}
foreach (var node in tree[currentNode])
{
visitedNodes.Add(node);
temp.Add(node);
// call method again with new values
FindPaths(node, tree, temp, visitedNodes);
}
// if node has no children left and is not a leaf node
// do something here?
}
else // we have reached a leaf node
{
paths.Add(temp.ToArray());
temp.RemoveAt(temp.Count - 1);
return paths;
}
return paths;
}
调用函数
paths = new List<int[]>();
var temp = new List<int>();
var vistedNodes = new List<int>();
var result = FindPaths(888, tree, temp, vistedNodes);
谁能帮我得到我想要的输出?如果可能的话,我想让它递归地工作
【问题讨论】:
-
您的字典定义了一个有向图,其中整数是顶点。 您的图表是否保证是非循环的?
-
如果不是,那么考虑
1 -> {2, 3}, 2 -> { 3 }, 3 -> { 2 },我们是从1开始遍历的。是你想要的解决方案{ [1, 2, 3], [1, 3, 2] }吗?还是因为3已经在第一个遍历中而拒绝第二次遍历? -
另外,一个建议:使用不可变数据类型。如果您停止使用可变集合,则可以更有效、更轻松地解决此类问题。
标签: c# dictionary recursion