C++实现简单的 图

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <assert.h>

using namespace std;

template<class V,class W,bool IsDirect = false>   //V顶点参数  W权值 默认无向图
class Graph{
  public:
    Graph(V* v,size_t n){
      _vertexs.resize(n);
      for(size_t i = 0;i < n;++i){
        _vertexs[i] = v[i];
      }
      _vv.resize(n);
      for(size_t i = 0;i < n;++i){
        _vv[i].resize(n,W());
      }
    }

    size_t GetVertexIndex(const V& v){
      for(size_t i = 0;i < _vertexs.size();++i){
        if(_vertexs[i] == v)
          return i;
      }
      assert(false);
      return 0;
    }

    void AddEdge(const V& src,const V& dst,const W& w){   //加和边长
      size_t srcindex = GetVertexIndex(src);
      size_t dstindex = GetVertexIndex(dst);

      _vv[srcindex][dstindex] = w;
      if(IsDirect == false)
        _vv[dstindex][srcindex] = w;
    }

    void _DFS(size_t srcindex,vector<bool>& visited){
      cout << _vertexs[srcindex] << ":" << srcindex << "->";
      visited[srcindex] = true;

      for(size_t i = 0;i < _vertexs.size();++i){
        if(_vertexs[srcindex][i] != W() && visited[i] == false){
          _DFS(i,visited);
        }
      }
    }
    void DFS(const V& src){ //深度优先,走递归!
      size_t srcindex = GetVertexIndex(src);
      vector<bool> visited;
      visited.resize(_vertexs.size(),false);
      _DFS(srcindex,visited);
      cout << endl;
    }

    void BFS(const V& src){ //广度优先
      size_t srcindex = GetVertexIndex(src);
      vector<bool> visited;
      visited.resize(_vertexs.size(),false);

      queue<int> q;
      q.push(srcindex);

      while(!q.empty()){
        int front = q.front();

        //防止一个值被包含多次
        if(visited[front] == false){
          cout << _vertexs[front] << ":" << front << "->";
          visited[front] = true;
          q.pop();
        }

        //下一层带进去
        for(size_t i = 0;i < _vertexs.size();++i){
          if(_vv[front][i] != W() && visited[i] == false){
            q.push(i);
          }
        }
      }
      cout << endl;
    }

  private:
    //顶点集合
    vector<V> _vertexs;
    //边的集合  -> 邻接矩阵
    vector< vector<W> > _vv;
};

测试代码

void TestGraph(){
  string a[] = {"tom","bob","amy","roin"};
  Graph<string,int> g(a,5);
  g.AddEdge("tom","amy",99);
  g.AddEdge("bob","roin",59);

  g.DFS("tom");
  g.BFS("tom");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

giturtle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值