赞
踩
无向图的Floyd算法+有向图的floyd算法
只需修改一行,
dist[u][v]=dist[v][u]= w;
改为
dist[u][v]= w;
代码:
#include<iostream> using namespace std; #define Max 9999 int n, m; int dist[Max][Max]; void Floyd() { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { for (int p = 0; p < n; ++p) { if (dist[j][p] > dist[j][i] + dist[i][p]) { dist[j][p] = dist[j][i] + dist[i][p]; } } } } } int main() { cout << "输入节点数: "; cin >> n; cout << "输入边数:"; cin >> m; for (int i = 0; i < n; ++i)//初始化各个数组 { for (int j = 0; j < n; ++j) { if (j == i) { dist[i][j] = 0; } else { dist[i][j] = Max; } } } int u, v, w; cout << "输入各条边的信息:" << endl; for (int i = 0; i < m; ++i) { cin >> u >> v >> w; dist[u][v] = dist[v][u] = w; } Floyd(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << dist[i][j] << " \t"; } cout << endl; } return 0; }
运行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。