Grafalgo
Library of useful data structures and algorithms
/Users/jst/src/grafalgo/cpp/graphAlgorithms/misc/bfs.cpp
00001 // usage: bfs
00002 //
00003 // Bfs reads a graph from stdin, and lists its vertices in breadth-first order
00004 // starting from vertex 1.
00005 //
00006 // This program is not bullet-proof. Caveat emptor.
00007 
00008 #include "stdinc.h"
00009 #include "Adt.h"
00010 #include "Util.h"
00011 #include "List.h"
00012 #include "Graph.h"
00013 
00014 using namespace grafalgo;
00015 
00016 void bfs(Graph&, vertex, List&);
00017 
00018 int main() {
00019         Graph g; cin >> g;
00020         List vlist(g.n());
00021         bfs(g,1,vlist);
00022         cout << vlist << endl;
00023 }
00024 
00025 void bfs(Graph& g, vertex s, List& vlist) {
00026         vertex u,v; edge e; List q(g.n());
00027         bool *mark = new bool[g.n()+1];
00028         for (u = 1; u <= g.n(); u++) mark[u] = false;
00029         q.addLast(s); mark[s] = true;
00030         while (!q.empty()) {
00031                 u = q.first(); q.removeFirst();
00032                 string s1;
00033                 vlist.addLast(u);
00034                 for (e = g.firstAt(u); e != 0; e = g.nextAt(u,e)) {
00035                         v = g.mate(u,e);
00036                         if (!mark[v]) { q.addLast(v); mark[v] = 1; }
00037                 }
00038         }
00039         cout << endl;
00040         delete [] mark;
00041 }
 All Classes Files Functions Variables Typedefs Friends