text cover

Data Abstraction and Problem Solving with C++

Walls and Mirrors

by Frank M. Carrano

Addison Wesley Logo

BFS.cpp

Go to the documentation of this file.
00001 
00018 #include "BFS.h"
00019 
00020 BFS::BFS(const Graph &g) : g(g), mark(g.getNumVertices(), -1),
00021             parents(g.getNumVertices(), 0), count(0)
00022 {
00023    startSearch();
00024 }  // end constructor
00025 
00026 void BFS::startSearch()
00027 {
00028    for (int v = 0; v < g.getNumVertices(); v++)
00029       if (mark[v] == -1)
00030          search(Edge(v,v, 0));
00031 }  // end startSearch
00032 
00033 
00034 void BFS::search(Edge e)
00035 {
00036    // create a queue to push edges
00037    queue<Edge> q;
00038 
00039    map<int, int> m;    // holds adjacency list of current vertex
00040    map<int, int>::iterator iter;
00041 
00042    q.push(e);
00043    while (!q.empty())
00044    {
00045       // get the edge at the front if the queue
00046       e = q.front();
00047 
00048       // pop the edge off the queue
00049       q.pop();
00050 
00051       // if the vertex w has not visited yet, visit it
00052       if (mark[e.w] == -1)
00053       {
00054          int v = e.v,
00055         w = e.w,
00056         weight = e.weight;
00057          mark[w] = count++;  // mark w visited
00058          parents[w] = v;     // store w's parent
00059 
00060          // go through adjacency list of w
00061          m = g.adjList[w];
00062          for (iter = m.begin(); iter != m.end(); iter++)
00063             // if w's neighbor vertices have not been visited,
00064             // push the edge on the queue
00065             if (mark[iter->first] == -1)
00066                q.push(Edge(w, iter->first, iter->second));
00067       }  // end if
00068    }  // end while
00069 }  // end search
00070 // End of implementation file

Generated on Sun Aug 27 22:27:07 2006 for AWLogo by  doxygen 1.4.6