图DFS运行时间慢

时间:2018-06-09 00:47:27

标签: javascript algorithm graph

我在为大量数据(n> 5,000,000)运行图DFS时遇到问题。问题是运行时间缓慢。谁能指出我应该改变的东西?我认为时间的复杂性是O(v * m)。谢谢!

Graph.prototype.dfs = function(graph, vertex, cb) {


  // track which node visited
  var visited = {};

  // Take graph as option
  var list = graph ? graph : this.list;

  // get initial nodes
  var currentNodes = list[vertex];

  // Invoke given function for inital node
  cb(vertex);

  // Mark vertex as visited
  visited[vertex] = true;

  // If there is no node to traverse return 
  if (currentNodes.length === 0) {
    return;
  }

  var stack = [...currentNodes];

  while (stack.length > 0) {

    // Get a node from stack
    var nextNode = stack.pop();
    if (!visited[nextNode]) {
      // Invoke given function
      cb(nextNode);
    }

    // Mark the vertex as visited
    visited[nextNode] = true;

    // Iterate adjacent nodes
    if (list[nextNode]) {
      for (var neighbor of list[nextNode]) {

        // If the vertex is not visited, push each nodes to stack
        if (!visited[neighbor]) { 
          stack.push(neighbor);
        }      
      } 
    } 

  }
}

1 个答案:

答案 0 :(得分:0)

DFS复杂度为O(V + M),因此如果它超过10秒则出现问题。我可以看到的第一件事是你正在向堆栈添加节点而不将它们标记为已访问,因此多个节点最终可以将相同的节点添加到堆栈。

尝试在visited[neighbor] = true;

之后添加stack.push(neighbor);