Skip to content

Commit

Permalink
BFS traversal on the province - Ignoring bridges
Browse files Browse the repository at this point in the history
  • Loading branch information
elijahbigk77 committed Apr 26, 2022
1 parent fe09369 commit dbe3b0d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
41 changes: 41 additions & 0 deletions province.cc
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,44 @@ void Province::minSpan(std::ostream & output) const {
output << _towns[minSpanTree[i]._tail]._name << std::endl;
}
}

std::vector<int> Province::bfs(int start) const {
// Initialize list of towns scheduled to visit
bool scheduled[_numberOfTowns];
for (int i = 0; i < _numberOfTowns; i ++) {
scheduled[i] = false;
}

// Initialize list of towns to visit with starting town
std::queue<int> toVisit;
toVisit.push(start);

scheduled[start] = true;
std::vector<int> results;

// While all towns have not been visited
while (!toVisit.empty()) {

// Remove current town from queue, add to results
int current = toVisit.front();
toVisit.pop();
results.push_back(current);

// Iterate over neighbors to current town
for (Town::RoadList::iterator neighbor =
_towns[current]._roads.begin();
neighbor != _towns[current]._roads.end();
neighbor ++) {

// If neighbor is not bridge and is not scheduled,
// add to results and schedule
if (!neighbor->_isBridge && !scheduled[neighbor->_head]) {
toVisit.push(neighbor->_head);
scheduled[neighbor->_head] = true;
}
}
}

return results;
}

7 changes: 7 additions & 0 deletions province.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,14 @@ class Province
private:

int smallest(double dist [], std::list <int> toVisit, int numTowns) const;

/**
* Conduct a breadth-first traversal on the province, ignoring bridges
* @param start Index of town to start traversal at
* @return - List of indices of towns in order of traversal
*/
std::vector<int> bfs(int start) const;

void dfsAux(int current, std::vector<int> & dfsTowns, bool visited []) const;

/**
Expand Down

0 comments on commit dbe3b0d

Please sign in to comment.