如何在不使用重复的情况下执行 DFS 时记录两个时间戳?

问题描述

在图中执行 DFS 时,使用两个时间戳来跟踪节点何时被访问以及节点的所有邻居何时都已被访问是很重要的。有时我们需要记录这两个时间戳。我已经知道如何使用重复来做到这一点。但是我在尝试不重复(使用例如循环和堆栈)来编写 DFS 函数时遇到了问题。

我已经尝试了常见的迭代 DFS 方法

    unsigned int time = 0;
    stack<int> nodeStack = stack<int>();
    vector<int> nodeVec = vector<int>(graph.size(),null); // null means not visited
    vector<pair<int,int>> nodeTimeStamp = vector<pair<int,int>>(graph.size(),pair<int,int>{0,0});
    list<int> firstTimeList = list<int>();
    list<int> lastTimeList = list<int>();
    bool isAcyclic = true;
    for (int i = 0; i < graph.size(); i++) {
        if (nodeVec.at(i) == null) {
            stack<int> nodeStack = stack<int>();
            nodeStack.push(i);
            firstTimeList.push_front(i);
            nodeTimeStamp.at(i).first = time ++;
            nodeVec.at(i) = visited;
            while (!nodeStack.empty()) {
                auto u = nodeStack.top();
                if (nodeVec.at(u) == discovered) {
                    lastTimeList.push_front(u);
                    nodeTimeStamp.at(u).second = time ++;
                    nodeStack.pop();
                }
                for (int j = 0; j < graph.at(u).size(); j++) {
                    int v = graph.at(u).at(j).first;
                    if (nodeVec.at(v) == null) {
                        nodeStack.push(v);
                        firstTimeList.push_front(v);
                        nodeTimeStamp.at(v).first = time ++;
                        nodeVec.at(v) = visited;
                    }
                    else
                        isAcyclic = false;
                }
                nodeVec.at(u) = discovered;
            }
        }
    }

它不起作用,因为它会在搜索时将一个节点的所有邻居推入堆栈。因此我们无法记录何时以这种方式访问​​了一个节点。能否请您帮我想想在执行 DFS 不使用重复时记录两个时间戳?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)