简体   繁体   English

改进的DFS的时间复杂度大O(使用DFS在迷宫中寻找路径)

[英]Time complecity big O of modifided DFS (using DFS to search for path in maze)

I wrote a program that solves maze that is not ideal (has 1 or more correct paths) using recursion DFS algorithm.我编写了一个程序,使用递归 DFS 算法来解决不理想的迷宫问题(有 1 条或多条正确路径)。 I have a problem with the time complexity of my program, becouse i read on the inte.net that the time complexity for DFS is O(v+n) where n is the number of node and v the number of edges.我的程序的时间复杂度有问题,因为我在 inte.net 上读到 DFS 的时间复杂度是 O(v+n),其中 n 是节点数,v 是边数。 In my case if i don't find the correct path i go back and go the other bath if there is a branching, so i am thinking how it will affect my time complexity.在我的例子中,如果我没有找到正确的路径,我返回 go 和 go 另一个浴室,如果有分支,所以我在想它会如何影响我的时间复杂度。 NOTE(mazes that i use are directed graph, so i can't go back and have to go from up to down)注意(我使用的迷宫是有向图,所以我不能 go 返回并且必须从上到下 go)

void DFS3 (int *visited, double **graf, int *paths, int **results, int n, int v, int end){
  visited [ v ] = 1;              
  if(v==end){     // if we find the end we write the table of paths (our path) to the table of results
    results[r][0]=k+1;                                      
    for(int j=1;j<k+1;j++)                                  
        results[r][j]=paths[j-1]; 
    results[r][k+1]=end;      // we write the last node (our wayout) to the table of results (it's not included in table of path)
    r++;                          
  visited[v]=0;    // we mark the last node as not visited
  }
  for(int i = 1; i < n*n+1; i++ ){
    if( ( graf [ v ][ i ] != 0 ) && visited [ i ] != 1 ){ 
        paths[k]=v;      // if we find the connection between node (a path) we write it to the paths and run the DFS3 of this node
        k++;    
        DFS3 ( visited, graf, paths,results, n, i, end); 
        }
  }
  paths[k]=0;      // if there is a dead end we go back to the first branching and delete the nodes that aren't correct path
  k--;
  visited[v]=0;      // we mark them as unvisited
}

In DFS, as long as you are marking the nodes as already visited, you can avoid visiting them again.在 DFS 中,只要将节点标记为已访问过,就可以避免再次访问它们。 So, while you still have to evaluate all the edges (and there can be O(|V|^2 many directed edges), you don't have to go back down old paths.因此,虽然您仍然需要评估所有边(并且可能有 O(|V|^2 条有向边),但您不必 go 返回旧路径。

If you want the shortest path through the maze (and not just the first one you happen to find), DFS is not great since you'd need to let it keep running to find all paths, then choose the shortest one.如果你想要穿过迷宫的最短路径(而不仅仅是你碰巧找到的第一条路径),DFS 不是很好,因为你需要让它继续运行以找到所有路径,然后选择最短的路径。 BFS will get you the shortest path first, but almost surely take longer to find a path through than DFS would. BFS 将首先为您找到最短路径,但几乎肯定比 DFS 需要更长的时间才能找到通过的路径。 But, it's also O(|V| + |E|)但是,它也是 O(|V| + |E|)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM