使用邻接矩阵不能正常工作的深度优先算法

时间:2015-12-01 04:56:13

标签: c++ depth-first-search

我尝试做深度优先算法。这就是我到目前为止所拥有的。

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);
        }
    }
}

我使用下面的图表来测试它:

Graph

具有以下邻接表:

enter image description here

使用该表我编写了我的主要功能:

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

有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:3)

您的代码中有两个问题。如果你很好地问编译器,第一个很容易找到。 g++ -Wall tells you第一个错误发生了DepthFirst,当你的意思是if (A[a][n] = 1)时,你写了if (A[a][n] == 1)。下一个错误是int nNodes = 8;中的main。您有一个包含11个节点的图表。修复它们和profit