Reputation: 23
This question probably is kind of silly, but I really need help.
I'm pretty new in programming and as far as I know, goto
is a thing that I should avoid in my code. And a couple of days ago I wrote this for my school task:
bool create_way(int start_index) {
if (start_index == members.get_size() - 1) {
flowToDrain.push_back(start_index);
return true;
}
find_any_way:
int max_index = INT_MIN;
int max_bandwidth = INT_MIN;
for (int i = 0; i < network[start_index].routes.get_size(); i++) {
int index = network[start_index].routes.find(i);
int bandwidth = network[index].bandwidth.find(start_index);
if (bandwidth > max_bandwidth && !network[index].visited) {
max_index = index;
max_bandwidth = bandwidth;
}
}
network[start_index].visited = true;
if (max_index != INT_MIN) {
if (!create_way(max_index)) goto find_any_way;
else {
flowToDrain.push_back(start_index);
return true;
}
}
else return false; }
I wrote goto
to keep in mind the logic of the algorithm, but now I'm really stuck with it. And since then I haven't came up with any idea how to get rid of this. I understand, that it should be a loop, probably with continue
, but I can't understand what expression to check in it.
Upvotes: 2
Views: 61
Reputation: 23508
This should work, though you should test it:
while(1) {
int max_index = INT_MIN;
int max_bandwidth = INT_MIN;
for (int i = 0; i < network[start_index].routes.get_size(); i++) {
int index = network[start_index].routes.find(i);
int bandwidth = network[index].bandwidth.find(start_index);
if (bandwidth > max_bandwidth && !network[index].visited) {
max_index = index;
max_bandwidth = bandwidth;
}
}
network[start_index].visited = true;
if (max_index != INT_MIN) {
if (!create_way(max_index)) continue;
else {
flowToDrain.push_back(start_index);
return true;
}
}
else return false;
}
Upvotes: 1