我试图使用邻接矩阵找到起始顶点和结束顶点之间的所有路径。我的图表未加权&无向。
我试图遵循这个算法但是,我被困在每个部分。
算法:
procedure FindAllPaths(u, dest)
{
push u to stack;
if(u == dest)
{
print stack;
}
else
{
foreach v that is adjacent with u and not in stack now
{
FindAllPaths(v, dest);
}
}
pop from stack;
}
我的代码:
void AdjacencyMatrix :: Find_All_Paths(int Origin, int Destination)
{
/*
MATRIX:
0 1 0 1 1
0 1 0 1 1
0 0 0 1 0
0 1 1 1 0
1 1 0 1 1
*/
//Push Origin to stack
Push_Vertex.push(Origin);
//Determine if Origin == Destination, if so, print the stack
if(Origin == Destination)
{
while(!Push_Vertex.empty())
{
cout << Push_Vertex.top() << " ";
Push_Vertex.pop();
}//while
cout << endl;
}//if
else
}//Find_All_Paths()
答案 0 :(得分:0)
您需要遍历与当前节点对应的行,以找到与其相邻的节点。这有点取决于你的邻接矩阵是如何实现的,但它看起来像这样:
for(int v = 0; v < n; v++)
{
if(adj[Origin][v] && !inStack[v])
{
Find_All_Paths(Origin, Destination);
}
}
adj
是您的邻接矩阵,如果adj[u][v]
到u
有一条边,则v
为真。 inStack
是一个布尔数组,用于存储顶点是否在堆栈中以允许快速检查。将数组初始化为false,并在将其插入堆栈时将与顶点对应的索引设置为true,并在将其弹出时将其设置为false。
完整代码:
void AdjacencyMatrix :: Find_All_Paths(int Origin, int Destination)
{
//Push Origin to stack
Push_Vertex.push(Origin);
inStack[Origin] = true;
//Determine if Origin == Destination, if so, print the stack
if(Origin == Destination)
{
while(!Push_Vertex.empty())
{
cout << Push_Vertex.top() << " ";
Push_Vertex.pop();
}//while
cout << endl;
}//if
else
{
for(int v = 0; v < n; v++)
{
if(adj[Origin][v] && !inStack[v])
{
Find_All_Paths(Origin, Destination);
}
}
}
Push_vertex.pop();
inStack[Origin] = false;
}//Find_All_Paths()