graph_internal.cpp
Go to the documentation of this file.
00001 #include "transform_graph/graph_internal.h"
00002 
00003 #include <algorithm>
00004 #include <map>
00005 #include <queue>
00006 #include <set>
00007 #include <string>
00008 
00009 using std::map;
00010 using std::queue;
00011 using std::set;
00012 using std::string;
00013 
00014 namespace transform_graph {
00015 namespace internal {
00016 Graph::Graph() : adjacencies_() {}
00017 
00018 void Graph::AddEdge(const std::string& v1, const std::string& v2) {
00019   adjacencies_[v1].insert(v2);
00020   adjacencies_[v2].insert(v1);
00021 }
00022 
00023 bool Graph::Path(const std::string& source, const std::string& target,
00024                  std::vector<std::string>* path) const {
00025   path->clear();
00026   if (!HasVertex(source) || !HasVertex(target)) {
00027     return false;
00028   }
00029 
00030   // Used to backtrack the path once the target has been found. Also used to
00031   // track whether a node has been visited or not. If a node has no parent, it
00032   // is either the source node or it has not been visited yet.
00033   map<string, string> parents;
00034 
00035   queue<string> queue;
00036   queue.push(source);
00037   while (!queue.empty()) {
00038     const string& current = queue.front();
00039 
00040     if (current == target) {
00041       string cur = target;
00042       path->push_back(cur);
00043       while (cur != source && parents.find(cur) != parents.end()) {
00044         cur = parents[cur];
00045         path->push_back(cur);
00046       }
00047       std::reverse(path->begin(), path->end());
00048       return true;
00049     }
00050 
00051     queue.pop();
00052     const set<string>& neighbors = adjacencies_.at(current);
00053     for (set<string>::iterator it = neighbors.begin(); it != neighbors.end();
00054          ++it) {
00055       string neighbor(it->data());
00056       if (neighbor != source && parents.find(neighbor) == parents.end()) {
00057         parents[neighbor] = current;
00058         queue.push(neighbor);
00059       }
00060     }
00061   }
00062 
00063   return false;
00064 }
00065 
00066 bool Graph::HasVertex(const std::string& v) const {
00067   return adjacencies_.find(v) != adjacencies_.end();
00068 }
00069 }  // namespace internal
00070 }  // namespace transform_graph


transform_graph
Author(s):
autogenerated on Sat Jun 8 2019 19:23:43