【算法与数据结构】图 -- 数组表示法

 

图的数组表示法

借助一个二维数组表示图,该二维数组的第i行,第j列的值表示从Node[i]到Node[j]

无向图(网):是否有边 / 权值,arr[i][j] == arr[j][i],无向图(网)的特性,矩阵关于对角线对称。

有向图(网):是否有弧 / 权值。

 

//图的数组表示法 //最大顶点个数
const int MAX_VERTEX = 100; //最大值
const int MAX_VALUE = (1 << 31) - 1; typedef struct _tagArcCell { int   adj;        //无向网,权值
    char  character;  //顶点信息,字符
}ArcCell, ArcCell_ARRAY[MAX_VERTEX][MAX_VERTEX]; typedef struct _tagGraph { char vexs[MAX_VERTEX];       //顶点向量
    ArcCell_ARRAY arcCellArray;  //节点数组
    int nodeNum;                 //顶点数
    int edgeNum;                 //边数
}Graph;

 

 

//根据点,获取该点在图中的位置
int Locate(Graph& graph, char ch) { for (int i = 0; i < graph.nodeNum; ++ i) { if (ch == graph.vexs[i]) { return i; } } return -1; }

 

void CreateGraph(Graph& graph) { //初始化无向网的值
    int num = 0; cout << "请输入图的顶点个数"; cin >> num; graph.nodeNum = num; cout << "请输入图的边数"; cin >> num; graph.edgeNum = num; cout << endl<<endl; cout<<"下面开始构造顶点向量"<<endl; for (int i = 0; i < graph.nodeNum; ++ i) { cout << "请输入每个顶点:"; char ch = 0; cin >> ch; graph.vexs[i] = ch; } cout << "\r\n顶点向量构造完毕\r\n\r\n"; cout << "下面开始初始化邻接矩阵\r\n"; for (int i = 0; i < graph.nodeNum; ++ i) { for (int j = 0; j < graph.nodeNum; ++ j) { graph.arcCellArray[i][j].adj = MAX_VALUE; } } cout << "\r\n邻接矩阵初始化完毕\r\n\r\n"; cout << "下面开始构造边,并为边分配权值\r\n"; for (int i = 0; i < graph.edgeNum; ++ i) { cout << "请先输入一个顶点:"; char ch = 0; cin >> ch; int nFrom = Locate(graph, ch); if (-1 == nFrom) { cout << "您输入的顶点不在此图上,请重新输入\r\n"; -- i; continue; } cout << "请输入另一个顶点:"; cin >> ch; int nTo = Locate(graph, ch); if (-1 == nTo) { cout << "您输入的顶点不在此图上,请重新输入本条边\r\n"; -- i; continue; } int adj = 0; cout << "请输入该边的权值:"; cin >> adj; graph.arcCellArray[nFrom][nTo].adj = graph.arcCellArray[nTo][nFrom].adj = adj; } cout <<endl<< "构造边和权值结束"<<endl<<endl; }

 

 

 

int _tmain(int argc, _TCHAR* argv[]) { Graph graph; CreateGraph(graph); return 0; }

 

 

 

  

转载于:https://my.oschina.net/u/926461/blog/350933

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值