bfs.h
Go to the documentation of this file.
1 /*
2  * This file is part of the alglib project.
3  *
4  * (c) Divyanshu Kakwani <divkakwani@gmail.com>
5  *
6  * For the full copyright and license information, please view the LICENSE file
7  * that was distributed with this source code.
8  */
9 
10 #pragma once
11 
12 #include <queue>
14 
15 
16 namespace alglib {
17 namespace graph {
18 
19 template<typename GraphType, typename OutputIter>
20 OutputIter _single_bfs(const GraphType& G,
21  const typename GraphType::vertex_type& start,
23  OutputIter dest) {
24 
25  typedef typename GraphType::vertex_type vertex_type;
26 
27  /* Maintains a list of unexplored vertices in order of their distance
28  * from the start vertex */
29  std::queue<vertex_type> frontier;
30 
31  /* Put `start` in the queue to start the bfs from */
32  frontier.push(start);
33 
34  while(!frontier.empty()) {
35  vertex_type inspect = frontier.front();
36  frontier.pop();
37  visited[inspect] = true;
38 
39  /* Put it into the output stream before inspection */
40  *dest++ = inspect;
41 
42  for(auto it = G.avbegin(inspect); it != G.avend(inspect); it++)
43  if(!visited(*it))
44  frontier.push(*it);
45  }
46  return dest;
47 }
48 
49 template<typename GraphType, typename OutputIter>
50 OutputIter single_bfs(const GraphType& G,
51  const typename GraphType::vertex_type& start,
52  OutputIter dest) {
53  return _single_bfs(G, start, vertex_property<GraphType, bool>(G, false), dest);
54 }
55 
56 
57 template<typename GraphType, typename OutputIter>
58 OutputIter bfs(const GraphType& G,
59  const typename GraphType::vertex_type& start,
60  OutputIter dest) {
61 
62  /* visited property initialized with false for each vertex */
63  vertex_property<GraphType, bool> visited(G, false);
64 
65  /* do the bfs of the start vertex first */
66  dest = _single_bfs(G, start, visited, dest);
67 
68  /* then others if they are not visited */
69  for(auto it = G.vbegin(); it != G.vend(); it++)
70  if(!visited(*it))
71  dest = _single_bfs(G, *it, visited, dest);
72 
73  return dest;
74 }
75 
76 
77 template<typename GraphType, typename OutputIter>
78 OutputIter bfs(const GraphType& G, OutputIter dest) {
79  return bfs(G, *G.vbegin(), dest);
80 }
81 
82 
83 } // end of graph namespace
84 } // end of alglib namespace
85 
86 
Definition: graph_property.h:20
Definition: bimap.h:17
OutputIter single_bfs(const GraphType &G, const typename GraphType::vertex_type &start, OutputIter dest)
Definition: bfs.h:50
OutputIter bfs(const GraphType &G, const typename GraphType::vertex_type &start, OutputIter dest)
Definition: bfs.h:58
OutputIter _single_bfs(const GraphType &G, const typename GraphType::vertex_type &start, vertex_property< GraphType, bool > &visited, OutputIter dest)
Definition: bfs.h:20