【发布时间】: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