C++ 我的广度优先算法工作不正常

C++ 我的广度优先算法工作不正常,c++,breadth-first-search,C++,Breadth First Search,我试着做一个广度优先算法。这就是我目前所拥有的 void BreadthFirst(int A[][100], int a, int nNodes) { // Local variables // Queue of nodes Q int visited[100]; for (int i = 0; i < nNodes; i++) visited[i] = 0; // initially all nodes are not visited // Initialize Q to be

我试着做一个广度优先算法。这就是我目前所拥有的

void BreadthFirst(int A[][100], int a, int nNodes)
{
// Local variables
// Queue of nodes Q
int visited[100];
for (int i = 0; i < nNodes; i++)
    visited[i] = 0; // initially all nodes are not visited
// Initialize Q to be empty
    int Q[100];
    int readPtr = 0, writePtr = 0;
    // Mark 'a' visited
    visited[a] = 1;
    // Write 'a'
    cout << char(a + 'a');
    // Enqueue (Q,a)
    Q[writePtr++] = a;
    // While 'a' is not empty do
    while (readPtr != writePtr)
    {
        for (int n = 0; n < nNodes; n++)
        {
            if (A[n][readPtr] == 1)
            {
                // If 'n' is not visited
                if (visited[n] == 0)
                {
                    // Mark 'n' as visited
                    visited[n] = 1;
                    // Write 'n'
                    cout << char(n + 'a');
                    // enqueue (Q,n)
                    Q[writePtr++] = n;
                }
            }
        }
        readPtr++;
    }
    cout << endl;
}
而且它不起作用。输出应该是

abehicjkdfg

相反,我得到了

abehicdfgjk


您能帮我修复它吗?

您在while循环中没有正确访问队列,而不是
A[n][readPtr]
在这个while循环中应该是
A[n][Q[readPtr]]

while (readPtr != writePtr)
{
    for (int n = 0; n < nNodes; n++)
    {
        if (A[n][Q[readPtr]] == 1)
        {
            // If 'n' is not visited
            if (visited[n] == 0)
            {
                // Mark 'n' as visited
                visited[n] = 1;
                // Write 'n'
                cout << char(n + 'a');
                // enqueue (Q,n)
                Q[writePtr++] = n;
            }
        }
    }
while(readPtr!=writePtr)
{
对于(int n=0;n在我看来,下面这一行应该重写

 if (A[n][readPtr] == 1)


您不应该在节点上迭代。您需要将第一个节点(a)添加到队列中,然后用您发现的任何节点填充队列。然后,for循环应该一直运行,直到它到达队列的末尾(在每个发现的节点上,它会越来越大)。您还需要将队列和访问的数组分开。它们不同。
 if (A[n][readPtr] == 1)
 if (A[Q[readPtr]][n] == 1)