【问题标题】:check if there is a cycle in directed graph CS50 tideman检查有向图CS50潮人中是否存在循环
【发布时间】:2020-06-14 16:31:58
【问题描述】:

为了检查循环,程序从图中的第一个节点到图中的每个锁定节点-> 检查它是否之前访问过,然后是一个循环,否则从检查的下一个节点递归地重复。 当我自己测试它时它可以工作,但是当我在潮人选举中使用它时它却没有。

问题说明:https://cs50.harvard.edu/x/2020/psets/3/tideman/

这个问题的目标是使用潮人投票算法从选举中选出获胜者。 CS50 ide 提供了测试功能 Check50 ,我正在尝试修复这些错误: 1.lock_pairs 如果创建循环则跳过最后一对 2.lock_pairs如果创建循环则跳过中间pair。

我的逻辑错了吗?

int graph[nodes_count][nodes_count];
bool check_cycle()
{
    //if a node is visited during checking cycles visited[]=true
    bool visited[nodes_count];
    bool circle = false;
    return gointo(circle, visited, 0);
}
bool gointo(bool &circle, bool visited[], int to)
{
// start trip form one node in the graph check if it have been visited ( Cycle )
    visited[to] = true;
    for (int n = 0; n < nodes_count; n++)
    {
        if (graph[to][n])
        {
            if (visited[n])
            {
                circle = true;
            }
            else
            {
                gointo(visited, n);
            }
            break;
        }
    }

    return circle;
}

我的完整解决方案:https://pastebin.com/sbua3EGA
感谢您的宝贵时间,抱歉英语不好:)

【问题讨论】:

  • 如果你能提供一小段代码来演示问题,而不是 250 行,你更有可能得到答案。
  • @Han-Kwang Nienhuys 好的。我放了整个程序,因为我用我自己的锁定对图及其作品尝试了这个功能
  • 这样更好,但你还是需要解释一下各种变量代表什么:pairs, locked, visited
  • @Han-Kwang Nienhuys 我会尽我所能,如果您想全面了解问题,请查看问题中的链接。

标签: c algorithm cs50 adjacency-matrix directed-graph


【解决方案1】:

您的算法在无向图中是正确的。在有向图中,它并不那么明显。

首先,从节点 0 开始,您可能不会访问所有节点。反例: 1 -> 0 -> 2

当你从节点 0 开始检查时,你根本不会访问节点 1。如果 1 也有一个循环的边缘,您将不会检测到它。这意味着,您应该为每个顶点创建一个循环,如果尚未访问它,请运行“gointo”函数。

通过上述更改,您最终可能会发现没有任何循环。

例如:

1 -> 2 -> 3

4 -> 2

如果您首先执行 gointo(1),您会将 1、2 和 3 标记为已访问。然后在调用 gointo(4) 时,您将“检测到一个循环”,因为 4 具有已标记顶点的边缘。这就是为什么您需要两个数组,一个告诉您已经访问过该节点,另一个告诉您在这个特定的 gointo 调用中访问了该节点。

代码应如下所示:

int graph[nodes_count][nodes_count];
bool check_cycle()
{
    //if a node is visited during checking cycles visited[]=true
    bool visited[nodes_count];
    bool this_call[nodes_count];
    bool circle = false;
    for (int i = 0; i < nodes_count; ++i)
    {
         if(!visited[i] && gointo(circle, visited, i))
           return true;
    }
    return false;
}
bool gointo(bool &circle, bool visited[], int to)
{
// start trip form one node in the graph check if it have been visited ( Cycle )
    visited[to] = true;
    this_call[to] = true;
    for (int n = 0; n < nodes_count; n++)
    {
        if (graph[to][n])
        {
            if (visited[n] && this_call[n])
            {
                circle = true;
            }
            else if(!visited[n])
            {
                gointo(visited, n);
            }
        }
    }
    this_call[to] = false;
    return circle;
}

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 2021-07-28
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多