当前位置: 面试刷题>> 图中两个点之间的路线 (经典算法题500道)


题目补充描述

题目: 在一个无向图中,给定两个节点(顶点)startend,以及图的所有边(以节点对的形式给出),请编写一个算法来找到从 startend 的一条路径(如果存在的话)。如果有多条路径,返回任意一条即可。如果不存在路径,则返回空或表示不存在的信息。

示例

输入

  • 图的边(以节点对形式给出):[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (1, 3)]
  • 起始节点:0
  • 目标节点:4

输出

  • 路径:[0, 1, 3, 4]

解题思路

这个问题可以通过深度优先搜索(DFS)或广度优先搜索(BFS)来解决。这里,我将使用深度优先搜索(DFS)来提供一个解决方案,因为它在找到一条路径时就能立即返回,而不需要遍历整个图。

PHP 示例代码

function findPathDFS($graph, $start, $end, &$visited = [], &$path = []) {
    $visited[$start] = true;
    $path[] = $start;

    if ($start == $end) {
        return $path;
    }

    foreach ($graph[$start] ?? [] as $neighbor) {
        if (!$visited[$neighbor]) {
            $result = findPathDFS($graph, $neighbor, $end, $visited, $path);
            if ($result) {
                return $result;
            }
        }
    }

    // 回溯
    array_pop($path);
    unset($visited[$start]);
    return [];
}

// 示例图的表示方式,使用邻接表
$graph = [
    0 => [1, 4],
    1 => [0, 2, 3],
    2 => [1, 3],
    3 => [2, 1, 4],
    4 => [3, 0]
];

$start = 0;
$end = 4;
$path = findPathDFS($graph, $start, $end);
print_r($path);

注意: PHP 示例中,我假设图以邻接表的形式给出,因为 PHP 的数组可以方便地表示这种结构。

Python 示例代码

def find_path_dfs(graph, start, end, visited=None, path=None):
    if visited is None:
        visited = set()
    if path is None:
        path = []

    visited.add(start)
    path.append(start)

    if start == end:
        return path

    for neighbor in graph[start]:
        if neighbor not in visited:
            result = find_path_dfs(graph, neighbor, end, visited, path)
            if result:
                return result

    # 回溯
    path.pop()
    visited.remove(start)
    return []

# 示例图的表示方式,使用邻接表
graph = {
    0: [1, 4],
    1: [0, 2, 3],
    2: [1, 3],
    3: [2, 1, 4],
    4: [3, 0]
}

start = 0
end = 4
path = find_path_dfs(graph, start, end)
print(path)

JavaScript 示例代码

function findPathDFS(graph, start, end, visited = new Set(), path = []) {
    visited.add(start);
    path.push(start);

    if (start === end) {
        return path;
    }

    for (let neighbor of graph[start] || []) {
        if (!visited.has(neighbor)) {
            const result = findPathDFS(graph, neighbor, end, visited, path);
            if (result) {
                return result;
            }
        }
    }

    // 回溯
    path.pop();
    visited.delete(start);
    return [];
}

// 示例图的表示方式,使用邻接表
const graph = {
    0: [1, 4],
    1: [0, 2, 3],
    2: [1, 3],
    3: [2, 1, 4],
    4: [3, 0]
};

const start = 0;
const end = 4;
const path = findPathDFS(graph, start, end);
console.log(path);

码小课 网站中有更多关于图论、算法和数据结构的相关内容分享给大家学习,欢迎访问以获取更多知识。

推荐面试题