1. 程式人生 > >圖的儲存c++實現

圖的儲存c++實現

圖的儲存

      c++ 實現

#include<iostream>

#include<String.h>

using namespace std;
class Node 
{
public :
char data; 
bool isvisited;
public :
Node(char d = 0)
{
data = d;
isvisited = false;
}
};
class MGraph
{
private:
Node *m_NodeArray;  //圖的空間
int *m_Matric;   //鄰接矩陣空間
int m_nodecount; //結點個數
int m_capacity;   //結點容量
public:
MGraph(int capacity)
{
m_capacity = capacity;
m_NodeArray = new Node[m_capacity];
m_Matric = new int[m_capacity*m_capacity];
m_nodecount = 0;
memset(m_Matric,0,m_capacity*m_capacity*sizeof(int));
}
~MGraph()
{
delete []m_NodeArray;
delete []m_Matric;
}
void AddMGraph(Node *node)   //新增結點
{
m_NodeArray[m_nodecount].data = node->data; 
        m_nodecount++;
}
void restNode()  //重置isvisited值為false
{
for(int i = 0 ; i < m_nodecount ; i++)
{
m_NodeArray[i].isvisited = false;
}
}
bool setValueDirectedMatric(int row,int col ,int val=1) //插入鄰接矩陣有向圖圖的權值預設為1   
{
m_Matric[row*m_capacity + col] = val;
return true;
}
bool setValueUndirectedMatric(int row ,int col ,int val=1) // 插入鄰接矩陣無向圖的權值預設為1
{
m_Matric[col*m_capacity + row] = val;
m_Matric[row*m_capacity + col] = val;
return true;
}
void printMatric()  //輸出鄰接矩陣
{
for(int i = 0 ; i<m_capacity ; i++)
{
for(int j = 0 ; j<m_capacity ; j++)
{
cout<<"  "<<m_Matric[i*m_capacity + j];
}
cout<<endl;
}
}
};
int main()
{
MGraph *m = new MGraph(7);
Node *node1 = new Node('A');Node *node2 = new Node('B');
Node *node3 = new Node('C');Node *node4 = new Node('D');
Node *node5 = new Node('E');Node *node6 = new Node('F');
Node *node7 = new Node('G');
m->AddMGraph(node1);m->AddMGraph(node2);m->AddMGraph(node3);
m->AddMGraph(node4);m->AddMGraph(node5);m->AddMGraph(node6);
m->AddMGraph(node7);         //新增圖的結點
m->setValueUndirectedMatric(0,1);m->setValueUndirectedMatric(0,2);   //A-B ,A-C
m->setValueUndirectedMatric(1,3);m->setValueUndirectedMatric(1,4);  //B-D,B-E
        m->setValueUndirectedMatric(3,4); m->setValueUndirectedMatric(2,5);//E-D,C-F
m->setValueUndirectedMatric(2,6); m->setValueUndirectedMatric(5,6); //C-G,F-G   預設權值都為1
cout<<endl;
cout<<"圖的鄰接矩陣"<<endl<<endl;
m->printMatric();
return 0;
}