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;
}

 

 

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值