GraphCycleDetector.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <unordered_map>
  18. #include <unordered_set>
  19. #include <glog/logging.h>
  20. namespace folly {
  21. namespace observer_detail {
  22. template <typename NodeId>
  23. class GraphCycleDetector {
  24. using NodeSet = std::unordered_set<NodeId>;
  25. public:
  26. /**
  27. * Add new edge. If edge creates a cycle then it's not added and false is
  28. * returned.
  29. */
  30. bool addEdge(NodeId from, NodeId to) {
  31. // In general case DFS may be expensive here, but in most cases to-node will
  32. // have no edges, so it should be O(1).
  33. NodeSet visitedNodes;
  34. dfs(visitedNodes, to);
  35. if (visitedNodes.count(from)) {
  36. return false;
  37. }
  38. auto& nodes = edges_[from];
  39. DCHECK_EQ(nodes.count(to), 0u);
  40. nodes.insert(to);
  41. return true;
  42. }
  43. void removeEdge(NodeId from, NodeId to) {
  44. auto& nodes = edges_[from];
  45. DCHECK(nodes.count(to));
  46. nodes.erase(to);
  47. if (nodes.empty()) {
  48. edges_.erase(from);
  49. }
  50. }
  51. private:
  52. void dfs(NodeSet& visitedNodes, NodeId node) {
  53. // We don't terminate early if cycle is detected, because this is considered
  54. // an error condition, so not worth optimizing for.
  55. if (visitedNodes.count(node)) {
  56. return;
  57. }
  58. visitedNodes.insert(node);
  59. if (!edges_.count(node)) {
  60. return;
  61. }
  62. for (const auto& to : edges_[node]) {
  63. dfs(visitedNodes, to);
  64. }
  65. }
  66. std::unordered_map<NodeId, NodeSet> edges_;
  67. };
  68. } // namespace observer_detail
  69. } // namespace folly