From 3ac2c2bf3b7b24d0d0e6add6ac27c486c439abce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Tue, 10 Feb 2015 11:23:06 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90BFS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TinySTL/Detail/Graph.impl.h | 23 ++++++++++++++++++++++- TinySTL/Graph.h | 8 +++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/TinySTL/Detail/Graph.impl.h b/TinySTL/Detail/Graph.impl.h index 25e6edb..ffe22ac 100644 --- a/TinySTL/Detail/Graph.impl.h +++ b/TinySTL/Detail/Graph.impl.h @@ -101,12 +101,33 @@ namespace TinySTL{ auto nodes = adjacent_nodes(start->first); func(*start); visited.insert(start->first); - for (auto& n : nodes){ + for (const auto& n : nodes){ if (visited.count(n.first) == 0)//has not visited DFS(n.first, func); } } template + void graph::BFS(const Index& index, visiter_func_type func){ + node *start = &(get_node(index)); + Unordered_set, EqualFunc> visited(7); + + auto nodes = adjacent_nodes(start->first); + func(*start); + visited.insert(start->first); + do{ + node_sets temp; + for (auto it = nodes.begin(); it != nodes.end(); ++it){ + if (visited.count(it->first) == 0){//has not visited + func(*it); + visited.insert(it->first); + auto s = adjacent_nodes(it->first); + temp.insert(temp.end(), s.begin(), s.end()); + } + } + nodes = temp; + } while (!nodes.empty()); + } + template string graph::to_string(){ string str; std::ostringstream oss; diff --git a/TinySTL/Graph.h b/TinySTL/Graph.h index 363abcd..fb41590 100644 --- a/TinySTL/Graph.h +++ b/TinySTL/Graph.h @@ -40,12 +40,14 @@ namespace TinySTL{ //node can be not in the graph virtual void add_node(const node& item, const node_sets& nodes) = 0; - //node of the index must in the graph - virtual void add_node(const Index& index, const node_sets& nodes) = 0; //virtual void delte_node(const node& item) = 0; + //node of the index must in the graph + virtual void add_node(const Index& index, const node_sets& nodes) = 0; + //virtual void delte_node(const Index& index) = 0; + void DFS(const Index& index, visiter_func_type func); - //virtual void BFS(visiter_func_type func) = 0; + void BFS(const Index& index, visiter_func_type func); node& new_node(const Index& index, const Value& val); void del_node(node *p);