【发布时间】:2013-04-24 17:01:25
【问题描述】:
如何从显示深度优先搜索的这部分代码中检测图形是否具有循环,并且图形是在邻接矩阵中实现的
// ------------------------------------------------------------
public void dfs() // depth-first search
{ // begin at vertex 0
int k = 0;
vertexList[0].wasVisited = true; // mark it
displayVertex(0); // display it
theStack.push(0); // push it
while (!theStack.isEmpty()) // until stack empty,
{
// get an unvisited vertex adjacent to stack top
int v = getAdjUnvisitedVertex(theStack.peek());
int x = nAdjVisitedVertex(v);
if (v == -1) // if no such vertex,
theStack.pop();
else // if it exists,
{
vertexList[v].wasVisited = true; // mark it
displayVertex(v); // display it
if (x == 2)
k++;
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;
if(k != 0)
System.out.println("not a cycle");
else
System.out.println("cycle");
} // end dfs
【问题讨论】:
-
您似乎很难提出好的问题。我们是一个非常有帮助的社区,但如果您提出一个深思熟虑的问题,表明您已经付出了一些努力,您会发现我们更有帮助。请仔细阅读该网站的常见问题解答。
-
这是有向图还是无向图?
-
@workInAFishBowl 抱歉,我在网上搜索过,但我今天需要这个!我只需要一个想法来自己实现它,而不是整个代码。
标签: java matrix graph cycle depth-first-search