c++実装は隣接テーブルと隣接マトリクスで図を格納する


ここではc++のコンテナvectorを用いて各ノードと情報を格納するここで我々の疎図は隣接テーブルでより良い稠密図を格納すると隣接マトリクスでより良い点を格納する
稠密図の隣接行列の実現
#ifndef DENSEGRAPH_MY_H_
#define DENSEGRAPH_MY_H_

#include
#include
#include

using namespace std;

//           

class DenseGraph_my
{
private:
	int n,m; //n        m      
	bool directed; //        ,                 
	vector< vector > g; //       ,      bool    int 

public:
	DenseGraph_my(int n,bool directed)
	{
		this->n = n;
		this->m = 0;
		this->directed = directed;
		//              
		for(int i = 0; i < n ; i++)
			g.push_back( vector (n,false));
	}

	~DenseGraph_my()
	{

	}

	int V() {return n;} //        
	int E() {return m;} //       

	//          
	bool hasEdge(int v, int w)
	{
		assert(v >= 0 && v < n);
		assert(v >= 0 && v < n);

		return g[v][w]; //            
	}


	//          
	void addEdge( int v ,int w)
	{
		assert(v >= 0 && v < n);
		assert(v >= 0 && v < n);

		if(hasEdge(v,w))
			return ;

		g[v][w] = true;

		if( !directed)
			g[w][v] = true;

		m++;
	}


	void show()
	{
		for(int i = 0 ; i < n ; i ++)
		{
			for( int j = 0 ; j <  n ; j ++)
				cout << g[i][j] << "\t";
			cout << endl;
		}
	}

};



#endif

疎図の隣接テーブルの実現
#ifndef SPARSEGRAPH_MY_H_
#define SPARSEGRAPH_MY_H_

//          
//        vector      

#include
#include
#include

using namespace std;

class SparseGraph_my
{
private:
	int n, m ;//n     m   
	bool directed; //        
	vector< vector > g; //           ,   true false


public:
	SparseGraph_my(int n, bool directed)
	{
		this->n = n;
		this->m = 0;
		this->directed = directed;
		for(int i = 0 ; i < n ; i++)
			g.push_back(vector()); //        ,       
	}

	~SparseGraph_my()
	{

	}

	int V(){ return n;}
	int E(){ return m;}

	bool hasEdge(int v , int w)
	{
		assert( v >= 0 && v < n);
		assert( w >= 0 && w < n);

		for(int i = 0 ; i < g[v].size() ; i ++)
			if(g[v][i] == w)
				return true;
		return false;
	}

	void addEdge(int v ,int w)
	{
		assert( v >= 0 && v < n);
		assert( w >= 0 && w < n);

		g[v].push_back(w); //   v            w   
		if( v != w && !directed)
			g[w].push_back(v);

		m++;

	}

	void show()
	{
		for(int i = 0 ; i < n ; i++)
		{
			cout << "vertex " << i << ":\t";
			for(int j = 0 ; j < g[i].size(); j++)
				cout << g[i][j] << "\t";
			cout << endl;
		}
	}



};


#endif