“要处理的事情”有名称吗?设计模式?
我偶尔会使用一种设计模式,但我不知道它叫什么。也许它有一个名字并且这里有人知道它?
当我想要遍历树状结构并对其所有节点执行某些操作时,我会使用它。它是这样的:
nodes_to_handle = [root_node]
while nodes_to_handle:
node = nodes_to_handle.pop()
# handle node
nodes_to_handle += node.get_neighbors()
请注意,该结构不一定是树;它可以是树。例如,此模式可用于在数组中进行洪水填充。
那么,这种设计模式有一个公认的名称吗?
There's a design pattern I use once in a while, and I don't know what's it called. Perhaps it has a name and someone here knows it?
It's something I use when I want to traverse a tree-like structure and do some action on all of its nodes. It goes something like this:
nodes_to_handle = [root_node]
while nodes_to_handle:
node = nodes_to_handle.pop()
# handle node
nodes_to_handle += node.get_neighbors()
Note that the structure doesn't have to be a tree; for example, this pattern can be used to do a flood-fill in an array.
So, is there an accepted name to this design pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您所得到的是比深度优先遍历更通用的模式:前沿列表。前沿列表是仍需要处理的元素的(排序或未排序)列表;该算法继续删除元素并处理它们,直到列表为空或满足某些其他终止条件。
我最喜欢的这种模式的例子是迪杰斯特拉算法。在 Dijkstra 中,前沿列表是一个优先级队列或堆,每次迭代时,最小值的元素都会从堆中弹出。
I think what you're getting at is a more general pattern than depth-first traversal: the frontier list. A frontier list is a (sorted or unsorted) list of elements that still require processing; the algorithm continues removing elements and processing them until the list is empty or some other termination criteria is met.
My favorite example of this pattern is dijkstra's algorithm. In Dijkstra's, the frontier list is a priority queue or heap, and the smallest-valued element is popped off the heap each iteration.
这看起来像深度优先遍历算法。 (因为您从末尾弹出列表)
它通常可以通过几种不同的方式实现:
#handle 节点
代码)。编辑:没有正确查看代码。 :)
This looks like the depth-first traversal algorithm. (since you pop the list from the end)
It can be implemented generically in a few different ways:
#handle node
code).Edit: Didn't look at the code properly. :)
这是深度优先图遍历。它是一个算法,而不是设计模式。 (来自 Jochen Ritzel 的评论。)
This is a depth-first graph traversal. It is an algorithm, not a design pattern. (From Jochen Ritzel's comment.)