【问题标题】:Get neighbouring vertices only using depth first search仅使用深度优先搜索获取相邻顶点
【发布时间】: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


【解决方案1】:

如果您将图形表示为邻接矩阵,那么您应该只从与顶点 A 对应的行中获取所有非零条目。

for(int j=0; j<nVerts; j++)
 if(adjMat[v][j]==1) System.out.println("vertex " + j);

所以你不需要 dfs。

【讨论】:

  • 有点吹毛求疵(抱歉),但即使 OP 清楚地提到了他的设置并且顶点之间的边数为 1,但在更一般的情况下,上面的 code 不会如果两个顶点之间有超过 1 条边,则工作。例如,如果 A->B 和 B->A,但使用了不同的边,那么它们共同的邻接矩阵条目将具有 2,而不是 1,并且 if 条件将失败。你的描述当然是对的——take all entries that are non zero from the row...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
相关资源
最近更新 更多