0

Following is how my graph is defined.

std::map< std::string, std::set<std::string> > g_db;

and Following is how I have written function to compute all the paths between two nodes, based on some of the previous question on this site.

void compute_all_paths(std::vector<std::string>& visited,  std::string& dest ) {  
    std::string back           = visited.back();    
    std::set<std::string> adj_stations = g_db.find(back)->second;

    for ( std::set<std::string>::iterator itr = adj_stations.begin();  itr != adj_stations.end(); ++itr )  {  
        if ( std::find(visited.begin(), visited.end(), *itr) != visited.end())
            continue;
        if (*itr == dest) {
            visited.push_back( *itr );    
            for ( std::vector<std::string>::size_type idx = 0; idx < visited.size(); idx++ ){  
                std::cout << visited[idx] << " ";  
            }
            std::cout << std::endl;  
            visited.erase( visited.begin() + (visited.size() - 1));    
            break;
        }
    }  
    for ( std::set<std::string>::iterator itr = adj_stations.begin();  itr != adj_stations.end();  itr++ )  {  
        if ( std::find(visited.begin(), visited.end(), *itr) != visited.end() || *itr == dest ) 
            continue;
        visited.push_back( *itr );    
        compute_all_paths(visited, dest );            
        visited.erase( visited.begin() + (visited.size() - 1));  
    }  
} 

My graph is very huge, this function is crashing with huge list of calls to recursive function with the following message:

Unhandled exception at 0x7c812afb in Railways.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x00033748

For small graph this works very well but not for huge graph.

Can anybody help me to find the issue.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Avinash
  • 12,851
  • 32
  • 116
  • 186

1 Answers1

4

Too many levels of recursivity can cause a stack overflow crash. That's why recursivity is not well suited for large data sets.

But all recursive calls can be reduced to loops. You should try removing recursive calls and replace them with loops.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625