BFS algorithm
| 31 | |
| 32 | // BFS algorithm |
| 33 | void Graph::BFS(int startVertex) { |
| 34 | visited = new bool[numVertices]; |
| 35 | for (int i = 0; i < numVertices; i++) |
| 36 | visited[i] = false; |
| 37 | |
| 38 | list<int> queue; |
| 39 | |
| 40 | visited[startVertex] = true; |
| 41 | queue.push_back(startVertex); |
| 42 | |
| 43 | list<int>::iterator i; |
| 44 | |
| 45 | while (!queue.empty()) { |
| 46 | int currVertex = queue.front(); |
| 47 | cout << "Visited " << currVertex << " "; |
| 48 | queue.pop_front(); |
| 49 | |
| 50 | for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) { |
| 51 | int adjVertex = *i; |
| 52 | if (!visited[adjVertex]) { |
| 53 | visited[adjVertex] = true; |
| 54 | queue.push_back(adjVertex); |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | int main() { |
| 61 | Graph g(4); |