【问题标题】:Path find algorithm for unsorted array of nodes未排序节点数组的路径查找算法
【发布时间】:2018-10-15 12:03:40
【问题描述】:

场景: 我有一张连接在一起的节点地图。

  • 我有所有节点的未排序数组。
  • 我有检查节点是否相互连接的功能(如果 node1 连接到 node2)。

function areNodesConnected(node1, node2) return true/false;

请求: 我正在寻找算法(伪代码)来使用此函数查找 2 个随机节点之间的路径。

结果应该是从节点 1 开始排序到节点 2 结束的节点数组。如果2个节点之间没有路径,则返回null。

注意事项:

  • 不需要最短路径
  • 如果路径较多,请先选择

感谢您的建议。 我不是要求完整的解决方案,而是从哪里开始解决这个问题的指针。

【问题讨论】:

  • 如何先保存每个节点的所有连接节点,然后从第一个随机节点开始,开始移动到每个其他连接节点,并跟踪每个路径中遍历的节点。如果某个节点重复,请停止递归,否则对当前节点执行相同操作。当到达第二个随机节点时,返回路径。

标签: sorting graph-algorithm path-finding maze


【解决方案1】:

我们可以使用 DFS(深度优先搜索)来找到答案。

让我们维护一个堆栈和一个访问过的数组来跟踪以前访问过的节点。我们还需要跟踪每个节点的父节点以获得最终答案。如上所述,使用函数 areNodesConnected(node1, node2) 检查边。

步骤

  1. 创建堆栈、父数组和访问数组。
  2. 将起始节点推入堆栈。
  3. 当堆栈不为空时:弹出堆栈并将连接到已弹出节点的所有节点推入堆栈。 (带函数 areNodesConnected)使用父数组跟踪节点的来源。
  4. 遍历父数组以获得最终答案。

伪代码

function findPath(int start, int end, int nodes):
    stack = Stack
    parent = array of integers to keep track of parents, set every value to -1 to start with
    vis = visited array of booleans to keep track of previous nodes

    stack.push(start)
    parent[start] = start // setting the starts parent to itself so we know when to stop searching.

    while stack is not empty:
        int x = stack.pop()
        for y in range 0 to nodes:
            if areNodesConnected(x, y) and not vis[y]: // checking if there is an edge from x to y
                stack.push(y)
                parent[y] = x; // store the parent of y
        vis[x] = true

    // now we have to print our final answer

    if parent[i] == -1:
        return null // there is no path

    list = List for final answer    

    for (int i = end; parent[i] != i; i = parent[i]): // recursively set i to it's parent until it is the starting node.
        list.add(i)

    // now lets add start
    list.add(start)

    return list

上述解决方案的唯一问题是列表与您想要的相反。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多