RobertS
RobertS

Reputation: 135

While loop, cout only the shortest path C++

I need only to have as output only the shortest path of graph from one vertice to another. The output of that funcition are all ways how to get from one vertice to another. Maybe I am just tired but I cant solve it, thanks for help. void findpaths(string src , string trgt ) { vector>path; vertex *source = name_to_vertex[src]; vertex *target = name_to_vertex[trgt];

    path.push_back(pair<vertex*, int>(source,0));
    queue< vector<pair<vertex*,int>> > q;
    q.push(path);
    int i = 1;
    while(!q.empty())
    {
        path=q.front();
        q.pop();

        vertex* last_nodeof_path= path[path.size()-1].first;
        if(last_nodeof_path==target)
        {
            if(path.back().second < 1) //second druha pozicia iteratora
            {cout << "path :";
 print_path(path);


                cout << "\n";
}
        }

        set<edge*>::iterator it;
        for(it= last_nodeof_path->edges.begin(); it != last_nodeof_path->edges.end(); ++it)
        {
            if(isadjacency_node_not_present_in_current_path((*it)->getOposite(last_nodeof_path),path))
            {   
                vector<pair<vertex*, int>> new_path(path.begin(),path.end());
                vertex* sused = (*it)->getOposite(last_nodeof_path);

                pair<vertex*, int> par(sused, (*it)->dist + new_path[new_path.size()-1].second);
                new_path.push_back(par);

                q.push(new_path);
            }
        }

    }cout<<"no path";


}

Upvotes: 0

Views: 114

Answers (1)

Gassa
Gassa

Reputation: 8844

Try adding a break; at the end of your if(last_nodeof_path==target) block. That way, you print the first answer you found and then end executing the main loop.

Upvotes: 1

Related Questions