我尝试做深度优先算法。这就是我到目前为止所拥有的。
void DepthFirst(int A[][100], int a, int visited[], int nNodes)
{
// Here I'm supposed to list all the nodes in the graph, starting with 'a'
// Mark 'a' visited (1)
visited[a] = 1;
// Write a
cout << char(a + 'a') << " , ";
// For each node n adjacent to 'a' do
for (int n = 0; n < nNodes; n++)
{
if (A[a][n] = 1)
{// If n is not visited, then
if (visited[n] == 0)
{
DepthFirst(A, n, visited, nNodes);
}
}
}
我使用下面的图表来测试它:
具有以下邻接表:
使用该表我编写了我的主要功能:
int main()
{
int a = 0;
int v[100] = { 0 };
int nNodes = 8;
int A[][100] =
{
{ 0,1,0,0,1,0,0,1,1,0,0 },
{ 1,0,1,0,0,0,0,0,0,0,0},
{ 0,1,0,1,1,1,0,0,0,0,0 },
{ 0,0,1,0,0,1,1,0,0,0,0 },
{ 1,0,1,0,0,0,0,1,0,1,0 },
{ 0,0,1,1,0,0,1,0,0,0,0 },
{ 0,0,0,1,0,1,0,0,0,0,0 },
{ 1,0,0,0,1,0,0,0,1,1,1 },
{ 1,0,0,0,0,0,0,1,0,0,1 },
{ 0,0,0,0,1,0,0,1,0,0,0 },
{ 0,0,0,0,0,0,0,1,1,0,0 },
};
DepthFirst(A, a, v, nNodes);
cout << endl;
return 0;
}
它不起作用。输出应为
a,b,c,d,f,g,e,h,i,k,j,
相反,我得到了
a,b,c,d,e,f,g,h
有人可以帮我解决吗?