【问题标题】:Various variations of the implementation of dfsdfs 实现的各种变体
【发布时间】:2021-03-19 18:50:23
【问题描述】:

假设我有一个具体的无向图: “1----2----3----4”。

算法“dfs”的后续实现有什么区别:

#include <iostream>
#include <vector>
using namespace std;
const int maxSize=4000;
vector<int> graph[maxSize];
bool visited0[maxSize];
void dfs0(int firstPoint, int previousPoint)
{
    visited0[firstPoint]=true;
    for(int secondPoint : graph[firstPoint])
    {
        if(visited0[secondPoint]==false)
        {
            dfs0(secondPoint, firstPoint);
        }
    }
    return;
}
bool visited1[maxSize];
void dfs1(int firstPoint, int previousPoint)
{
    visited1[maxSize]=true;
    for(int secondPoint : graph[firstPoint])
    {
        if(secondPoint==previousPoint)
        {
            continue;
        }
        dfs1(secondPoint, firstPoint);
    }
    return;
}
bool visited2[maxSize];
void dfs2(int firstPoint, int previousPoint)
{
    visited2[firstPoint]=true;
    for(int secondPoint : graph[firstPoint])
    {
        if(secondPoint==previousPoint)
        {
            continue;
        }
        if(visited2[secondPoint]==false)
        {
            dfs2(secondPoint, firstPoint);
        }
    }
    return;
}
int main()
{
    dfs0(1, -1);
    dfs1(1, -1);
    dfs2(1, -1);
    return 0;
}

如果更准确地说,我想知道何时(在哪些情况下)我应该使用命令分支:

if(visited0[secondPoint]==false)
{
    dfs0(secondPoint, firstPoint);        (Variation #1)
}

if(secondPoint==previousPoint)
{
    continue;
}
dfs1(secondPoint, firstPoint);        (Variation #2)

if(secondPoint==previousPoint)
{
    continue;
}
if(visited2[secondPoint]==false)
{
    dfs2(secondPoint, firstPoint);        (Variation #3)
}

请描述每个变体(变体 #1、变体 #2、变体 #3)。

在哪些情况下我必须使用变体 #1

在哪些情况下我必须使用变体 #2

在哪些情况下我必须使用变体 #3

下一个命令分支的出现(放在下面)将如何影响算法的各种实现 "dfs" (dfs0(1, -1), dfs1(1, -1), dfs2(1, -1)):

Use the parameter "visited" in dependence of the version of the algorithm "dfs": either "visited0", or "visited1", or "visited2".

How is it important to use this command-branching at the beginning of the various implementations of the algorithm "dfs" (dfs0(1, -1), dfs1(1, -1), dfs2(1, -1))?

if(visited0[firstPoint]==true)
{
    return;
}

谢谢。

【问题讨论】:

    标签: c++ algorithm graph depth-first-search


    【解决方案1】:

    Variation 1Variation 3 之间没有逻辑上的区别,但 Variation 3 是优化版本,因为它会避免 不需要的递归调用,如果涉及 large 测试用例,这可能是一个很大的问题。这可能会不必要地消耗更多内存。

    变体 2 在逻辑上与其他两个变体不同,因为它允许在 DFS 期间多次访问节点。

    变体 2 中节点被访问的次数将取决于图的邻接矩阵/列表。

    Variation 1Variation 3 中使用 command-branching 将不起作用,因为我们已经在检查节点是否有之前访问过,但它肯定会使Variation 2正常工作(根据DFS的定义:几乎访问每个节点一次。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多