可以肯定地说,在您要求查找到达图表中特定节点的最小跳数的问题中,BFS优于DFS吗?
我理解,在搜索问题中,任务是搜索节点,BFS或DFS更好将取决于图的性质。例如,如果您的图形是一个家族树,并且您正在寻找一个活着的人,那么最好使用DFS,因为该节点更可能在图中很深。相反,如果您正在寻找多年前去世的人,那么BFS将是理想的。
然而,在这种情况下,我觉得,即使DFS要快速找到节点,它仍然需要回溯,并找到到达目的地的所有其他路径,然后在它们之间进行比较以找到跳数最少的路径。另一方面,对于BFS,第一次找到节点时,可以得出结论,这确实是跳数最少的路径。
我的问题是
我的代码使用DFS
/* Depth First Search */
public int DFSrecursive(Vertex source, Vertex destination)
{
if(source == destination)
{
source.visited = false;
return 0;
}
int min = Integer.MAX_VALUE-1;
for(int i = 0;i<source.neighbors.size();i++)
{
Vertex neighbor = source.neighbors.get( i );
if(neighbor.visited == false)
{
neighbor.visited = true;
min = Math.min( min, DFSrecursive( neighbor, destination )+1 );
}
}
source.visited = false;
return min;
}
我的代码使用BFS
/* Breadth First Search */
public int distBFSHashtable(Vertex source, Vertex destination)
{
/* Everything in the queue will be unique, because if, already visited, I don't push into queue.
* Also, at the time of pushing itself, I made it's visited to be true */
Queue<Vertex> toprocess = new LinkedList<>();
toprocess.add( source );
source.visited = true;
/* This table gives the distance of each vertex from source */
Hashtable<Vertex, Integer> distanceTable = new Hashtable<>();
distanceTable.put( source, 0 );
while(toprocess.size() > 0 )
{
Vertex current = toprocess.poll();
for(int i = 0;i<current.neighbors.size();i++)
{
Vertex neighbor = current.neighbors.get( i );
// distanceTable.put( neighbor, distanceTable.get( current )+1 );
if(neighbor.visited == false)
{
neighbor.visited = true;
toprocess.add( neighbor );
distanceTable.put( neighbor, distanceTable.get( current )+1 );
}
if(neighbor == destination)
return distanceTable.get( neighbor );
}
}
return -1;
}