数据结构之图

一. 常见算法模板

1. 基础代码,具体释义后序有空补充

头文件

#ifndef __GRAPH__H__
#define __GRAPH__H__

#include <algorithm>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

struct Edge;

struct Node {
  int _val; // 自己的数据项
  int _in; // 一个点的入度,别人进到自己有多少个点,有几个点指向自己
  int _out;                   // 一个点的出度,这个点指向几个点
  std::vector<Node *> _next;  // 从当前节点发散出去的节点的合集
  std::vector<Edge *> _edges; // 拿几条边是属于该节点的

  Node(int val) : _val(val) {
    _in = 0;
    _out = 0;
  }
};

struct Edge {
public:
  int _weight; // 权重
  Node _from;
  Node _to;

public:
  Edge(int weight, Node from, Node to)
      : _weight(weight), _from(from), _to(to) {}
};

class MySets {
public:
  std::unordered_map<Node *, std::list<Node *>> _setMap;
  MySets(std::list<Node *> nodes) {
    // 一开始每一个集合的节点只有自己
    for (auto node : nodes) {
      std::list<Node *> myset;
      myset.push_back(node);
      _setMap.insert(make_pair(node, myset));
    }
  }

  bool isSameSet(Node *from, Node *to);
  void unionSet(Node *from, Node *to);
};

class Graph {
public:
  std::map<int, Node *> _nodes;
  std::set<Edge *> _edges;
  std::list<Node *> _unionNodes;

public:
  Graph() {}
  ~Graph() {}

  // 宽度优先遍历
  void bfs(Node *node);
  void dfs(Node *node);
  void showMap();

  // 拓扑排序
  std::list<Node *> sortedToPology(Graph *graph);

  // 针对于无向图的两种算法,最小生成树
  std::set<Edge *> kruskalMST(Graph *graph);
  std::set<Edge *> primMST(Graph *graph);

  std::unordered_map<Node *, int> dijkstral(Node *head);

private:
  Node *
  getMinDistanceAndUnselectNode(std::unordered_map<Node *, int> distanceMap,
                                std::set<Node *> selectNodes);
};

#endif // !__GRAPH__H__

源文件

#include "Graph.h"
#include <queue>
#include <unordered_map>

Graph *createGraph(int (*arr)[3], int rawSize, int colSize) {
  if (arr == nullptr) {
    return nullptr;
  }

  Graph *graph = new Graph;
  for (int i = 0; i < rawSize; ++i) {
    int weight = arr[i][0];
    int from = arr[i][1];
    int to = arr[i][2];

    if (!(graph->_nodes.find(from) != graph->_nodes.end())) {
      graph->_nodes.insert(std::make_pair(from, new Node(from)));
    }

    if (!(graph->_nodes.find(to) != graph->_nodes.end())) {
      graph->_nodes.insert(std::make_pair(to, new Node(to)));
    }

    auto iter = graph->_nodes.find(from);
    Node *fromNode = iter->second;
    iter = graph->_nodes.find(to);
    Node *toNode = iter->second;

    Edge newEdg(weight, *fromNode, *toNode);
    // 智能指针的写法需要vector中的类型也是对应智能指针的对象才可以
    // std::shared_ptr<Edge> newEdge(new Edge(weight, *fromNode, *toNode));

    fromNode->_next.push_back(toNode);
    fromNode->_out++;
    toNode->_in++;
    fromNode->_edges.push_back(&newEdg);
    graph->_edges.insert(&newEdg);
  }

  return graph;
}

void Graph::dfs(Node *node) {
  if (node == nullptr) {
    return;
  }

  std::stack<Node *> myStack;
  std::set<Node *> mySet;

  myStack.push(node);
  mySet.insert(node);
  std::cout << "cur val = " << node->_val << std::endl;

  while (!myStack.empty()) {
    Node *curNode = myStack.top();
    myStack.pop();

    for (auto iter : curNode->_next) {
      auto it = mySet.find(iter);
      if (it == mySet.end()) {
        myStack.push(curNode);
        myStack.push(iter);
        mySet.insert(iter);
        std::cout << "cur val = " << iter->_val << std::endl;
        break;
      }
    }
  }
}

void Graph::showMap() {
  for (auto iter : _nodes) {
    std::cout << "val = " << iter.first << " Node.val = " << iter.second->_val
              << std::endl;
  }
}

void Graph::bfs(Node *node) {
  if (node == nullptr) {
    return;
  }

  std::queue<Node *> myQueue;
  std::set<Node *> mySet;

  myQueue.push(node);
  mySet.insert(node);

  while (!myQueue.empty()) {
    Node *curNode = myQueue.front();
    myQueue.pop();
    std::cout << "cur val = " << curNode->_val << std::endl;

    for (auto cur : curNode->_next) {
      // std::cout << "cur val = " << cur->_val <<   std::endl;
      auto it = mySet.find(cur);
      if (it == mySet.end()) {
        myQueue.push(cur);
        mySet.insert(cur);
      }
    }
  }
}

void test() {
  int arr[8][3] = {{7, 1, 8}, {1, 1, 2}, {3, 1, 4}, {1, 8, 7},
                   {5, 2, 7}, {4, 2, 6}, {2, 4, 6}, {1, 7, 6}};

  Graph *graph = createGraph(arr, 8, 3);
  graph->showMap();
  auto iter = graph->_nodes.find(1);
  Node *node1 = iter->second;
  // graph->bfs(node1);
  graph->dfs(node1);
}

bool MySets::isSameSet(Node *from, Node *to) {
  auto iter = _setMap.find(from);
  std::list<Node *> fromSet = iter->second;
  iter = _setMap.find(to);
  std::list<Node *> toSet = iter->second;
  return fromSet == toSet;
}

void MySets::unionSet(Node *from, Node *to) {
  auto iter = _setMap.find(from);
  std::list<Node *> fromSet = iter->second;
  iter = _setMap.find(to);
  std::list<Node *> toSet = iter->second;

  for (auto node : toSet) {
    fromSet.push_back(to);
    _setMap.insert(std::make_pair(node, fromSet));
  }
}

std::set<Edge *> Graph::kruskalMST(Graph *graph) {
  std::set<Edge *> result;
  if (graph == nullptr) {
    return result;
  }

  MySets myset(graph->_unionNodes);
  std::priority_queue<Edge *> myPriortQueue;
  for (auto edge : graph->_edges) {
    myPriortQueue.push(edge);
  }

  while (!myPriortQueue.empty()) {
    Edge *edge = myPriortQueue.top();
    myPriortQueue.pop();

    if (!myset.isSameSet(&edge->_from, &edge->_to)) {
      result.insert(edge);
      myset.unionSet(&edge->_from, &edge->_to);
    }
  }
  return result;
}

std::set<Edge *> Graph::primMST(Graph *graph) {
  std::set<Edge *> myresult; // 存储最小生成树的边集合

  std::priority_queue<Edge *> mypriorityQueue; // 优先队列,用于按边的权值大小进行排序
  std::unordered_set<Node *> myset; // 无序集合,用于记录已经访问过的节点

  for (auto node : graph->_nodes) { // 遍历图中的所有节点
    if (myset.find(node.second) != myset.end()) { // 如果节点已经被访问过,则跳过
      myset.insert(node.second); // 将当前节点加入已访问集合

      for (auto edge : node.second->_edges) { // 遍历当前节点的所有边
        mypriorityQueue.push(edge); // 将边加入优先队列
      }

      while (!mypriorityQueue.empty()) { // 当优先队列非空时执行循环
        auto edge1 = mypriorityQueue.top(); // 取出优先队列中权值最小的边
        mypriorityQueue.pop(); // 弹出队列中的顶部元素
        auto node1 = &edge1->_to; // 获取边的目标节点

        if (myset.find(node1) != myset.end()) { // 如果目标节点未被访问过
          myset.insert(node1); // 将目标节点加入已访问集合
          myresult.insert(edge1); // 将当前边加入最小生成树的边集合

          for (auto nextEdge : node1->_edges) { // 遍历目标节点的所有边
            mypriorityQueue.push(nextEdge); // 将这些边加入优先队列,用于下一次循环
          }
        }
      }
    }
  }

  return myresult; // 返回最小生成树的边集合
}


Node *Graph::getMinDistanceAndUnselectNode(
    std::unordered_map<Node *, int> distanceMap, std::set<Node *> selectNodes) {
  Node *result = nullptr;
  int minDistance = INT_MAX;

  for (auto entry : distanceMap) {
    int distance = entry.second;
    Node *node1 = entry.first;

    if ((selectNodes.find(node1) != selectNodes.end()) &&
        distance < minDistance) {
      result = node1;
      minDistance = distance;
    }
  }
  return result;
}

std::unordered_map<Node *, int> Graph::dijkstral(Node *head) {
  std::unordered_map<Node *, int> distanceMap;
  if (head == nullptr) {
    return distanceMap;
  }
  // 从head出发到所有店的最小距离
  // key:从head出发到达key
  // value:从head出发到达key的最小距离
  // 如果在表中,没有T的记录,含义是从head出发到这个点的距离为正无穷

  // 首先第一步是把头结点放到hashmap中
  distanceMap.insert(std::make_pair(head, 0));
  // 创建一个set集合用来记录所有已经被走过的点
  std::set<Node *> selectNodes;
  Node *minhead = getMinDistanceAndUnselectNode(distanceMap, selectNodes);

  // 在选择的节点集合非空时进行循环
  while (minhead != nullptr) {
    int distance = distanceMap.find(minhead)->second;
    // 遍历当前选择节点的边
    for (auto edges : minhead->_edges) {
      Node *toNode = &edges->_to;
      // 如果目标节点已经在距离表distanceMap中,则更新其距离值
      if (distanceMap.find(toNode) != distanceMap.end()) {
        distanceMap.insert(std::make_pair(toNode, distance + edges->_weight));
      }
      // 否则,将目标节点及其距离插入distanceMap
      distanceMap.insert(
          std::make_pair(&edges->_to, std::min(distanceMap.find(toNode)->second,
                                               distance + edges->_weight)));
    }
    // 将当前选择节点插入已选择节点集合中
    selectNodes.insert(minhead);
    // 获取下一个最小距离且未选择的节点
    minhead = getMinDistanceAndUnselectNode(distanceMap, selectNodes);
  }

  return distanceMap;
}

// 拓扑排序
std::list<Node *> Graph::sortedToPology(Graph *graph) {
  std::list<Node *> result;
  if (graph == nullptr) {
    return result;
  }

  // 创建一个map用来记录当前所有点以及它的当前入度
  std::unordered_map<Node *, int> inMap;
  // 创建一个队列用来保存当前度为0的节点
  std::queue<Node *> zeroInQueue;

  // 遍历整个图的所有节点,将每个节点以及其入度记录在inmap中,并且将度为0的节点放在队列中
  for (auto node : graph->_nodes) {
    inMap.insert(std::make_pair(node.second, node.second->_in));
    if (node.second->_in == 0) {
      zeroInQueue.push(node.second);
    }
  }

  // 当0度的队列不为空的时候,进行去0度进行排序
  while (!zeroInQueue.empty()) {
    // 先从0度的队列中取出来一个节点
    auto node = zeroInQueue.front();
    zeroInQueue.pop();
    // 将其压在结果的链表当中
    result.push_back(node);

    // 遍历所有与这个节点相连接的带你,并将其插入到inmap中,并将其在inmap中的度减一
    for (auto next : node->_next) {
      inMap.insert(std::make_pair(next, inMap.find(next)->second - 1));
      // 如果减一之后此节点的度编变成了0,那么则将其插入到0度的队列当中
      if (inMap.find(next)->second == 0) {
        zeroInQueue.push(next);
      }
    }
  }
  return result;
}

int main(int argc, const char **argv) {

  test();

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值