图的存储
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;
}