The first width algorithm is not working properly

I tried to make the first width algorithm. And that is what I still have.

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

I used the following graph to check it out:

Graph

which has the following adjacency table:

Adjacency Table

Using this table, I wrote my main function:

int main()
{
int nNodes = 11;
int a = 0;
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 },
};
BreadthFirst(A, a, nNodes);
return 0;
}

And it does not work. The exit should be

abehicjkdfg

Instead i get

abehicdfgjk

Can you help me fix this please?

+4
source share
2 answers

you are not accessing the queue correctly in your while loop, and not in A[n][readPtr]it should be A[n][Q[readPtr]]in this while loop

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;
            }
        }
    }
+3
source

In my opinion, the line below should be rewritten,

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

to

 if (A[Q[readPtr]][n] == 1)
+1
source

Source: https://habr.com/ru/post/1618083/


All Articles