繁体   English   中英

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

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

我编写了一个程序,使用递归 DFS 算法来解决不理想的迷宫问题(有 1 条或多条正确路径)。 我的程序的时间复杂度有问题,因为我在 inte.net 上读到 DFS 的时间复杂度是 O(v+n),其中 n 是节点数,v 是边数。 在我的例子中,如果我没有找到正确的路径,我返回 go 和 go 另一个浴室,如果有分支,所以我在想它会如何影响我的时间复杂度。 注意(我使用的迷宫是有向图,所以我不能 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
}

在 DFS 中,只要将节点标记为已访问过,就可以避免再次访问它们。 因此,虽然您仍然需要评估所有边(并且可能有 O(|V|^2 条有向边),但您不必 go 返回旧路径。

如果你想要穿过迷宫的最短路径(而不仅仅是你碰巧找到的第一条路径),DFS 不是很好,因为你需要让它继续运行以找到所有路径,然后选择最短的路径。 BFS 将首先为您找到最短路径,但几乎肯定比 DFS 需要更长的时间才能找到通过的路径。 但是,它也是 O(|V| + |E|)

暂无
暂无

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

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