0

I am writing a program that uses the recursive BFS algorithm to determine dependencies in an undirected graph. I am using a 5x5 array as an adjacency matrix to represent the graph. While debugging, I noticed that my "stack s" variable is remaining empty while running and I cannot figure where the logical error is. Please note that I am new to programming and if I have made any fundamental mistakes or misunderstandings in the code please let me know.

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

void TaskOrderHelper(int A[5][5], int start, vector<bool> visited, stack<int> s)
{
    for(int i = 0; i < 5; i++)
    {
        if(A[start][i] == 1 && visited[i] == false)
        {
            visited[i] = true;
            TaskOrderHelper(A, i, visited, s);
            s.push(i);
        }
    }
}
vector<int> taskOrder(int A[5][5], int start)
{
    vector<bool> visited(5,false);
    stack<int> s;
    vector<int> result;

    for(int i = 0; i < 5; i++)
    {
        visited[i] = true;
    }
    visited[start] = true;

    TaskOrderHelper(A, start, visited, s);

    while(!s.empty())
    {
        int w = s.top();
        result.push_back(w);
        s.pop();
    }
    return result;
}
int main()
{
    int A[5][5] = 
    {
        {0,1,1,0,0},
        {1,0,0,1,0},
        {1,0,0,0,1},
        {0,1,0,0,1},
        {0,0,1,1,0}
    };
    vector<int> result = taskOrder(A, 0);

    for(auto i: result)
    {
        cout << i;
    }
    return 0;
}
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
bpsNomad
  • 37
  • 4

2 Answers2

1

There are other issues here with the BFS but to answer your question on why your stack is empty, your stack is being passed by value, to modify a parameter passed into another function you'll want to pass by reference. Try changing TaskOrderHelper to

void TaskOrderHelper(int A[5][5], int start, vector<bool>& visited, stack<int>& s)

purplewhales
  • 61
  • 1
  • 4
1

Line 26 you set visited[i] = true; for all visiteds, your recursive if statement never hits

Ripread
  • 330
  • 2
  • 10