【发布时间】:2023-03-14 23:42:01
【问题描述】:
如何仅使用深度优先搜索获取相邻顶点?
我正在使用深度优先搜索算法来搜索有向图,我的问题是我想让它只返回我的起始顶点的邻居,而不是继续进行直到它到达死胡同。
假设我有顶点(A、B、C、D) 和边缘((A -> B),(A -> C),(C -> D)) 而且我想要顶点 A 的所有邻居,而不是得到 B 和 C,即使 D 不与 A 相邻,它也包括 D?
public void dfs(int x) // depth-first search
{ // begin at vertex 0
vertexList[x].wasVisited = true; // mark it
displayVertex(x); // display it
theStack.push(x); // push it
while( !theStack.isEmpty() ) // until stack empty,
{
// get an unvisited vertex adjacent to stack top
int v = getAdjUnvisitedVertex( theStack.peek() );
if(v == -1) // if no such vertex,
theStack.pop();
else // if it exists,
{
vertexList[v].wasVisited = true; // mark it
displayVertex(v); // display it
theStack.push(v); // push it
}
} // end while
// stack is empty, so we're done
for(int j=0; j<nVerts; j++) // reset flags
vertexList[j].wasVisited = false;
} // end dfs
// ------------------------------------------------------------
// returns an unvisited vertex adj to v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j;
System.out.println("Found unvisited vertex");
return -1;
} // end getAdjUnvisitedVertex()
我知道我可以在创建 Vertex 时只存储它的邻居,但这意味着如果我将来必须进行更改,我将不得不进行很多更改,如果有人对如何指导我有任何想法在正确的方向,我将非常感激!
【问题讨论】:
-
如果你真的需要使用深度优先搜索,我会假设所有相邻的顶点都有一定的深度,即当你到达它们时,堆栈有一定的大小。
标签: java graph depth-first-search vertex