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");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章