-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyd.cpp
114 lines (112 loc) · 2 KB
/
floyd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "floyd.h"
Floyd::Floyd() :distances(NULL),routes(NULL){}
Floyd::Floyd(int n):number(n)
{
distances = new int*[number];
routes = new unsigned int*[number];
for(unsigned int i = 0;i<number;i++)
{
distances[i]=new int[number];
routes[i]=new unsigned int[number];
}
for(unsigned int i = 0;i<number;i++)
{
for(unsigned int j = 0;j<number;j++)
{
routes[i][j]=j+1;
}
}
}
Floyd::~Floyd()
{
for(unsigned int i = 0;i<number;i++)
{
delete []distances[i];
delete []routes[i];
}
delete []distances;
delete []routes;
}
Floyd::Floyd(Floyd& f)
{
number = f.number;
distances = new int*[number];
routes = new unsigned int*[number];
for(unsigned int i = 0;i<number;i++)
{
distances[i]=new int[number];
routes[i]=new unsigned int[number];
}
for(unsigned int i = 0;i<number;i++)
for(unsigned int j = 0;j<number;j++)
{
distances[i][j]=f.distances[i][j];
routes[i][j]=f.routes[i][j];
}
}
void Floyd::setNumber(int n)
{
number = n;
}
void Floyd::input()
{
cout<<"Input adjacency matrix (infinite = max(a[i][j])+1) : "<<endl;
for(unsigned int i = 0;i<number;i++)
for(unsigned int j = 0;j<number;j++)
{
cin>>distances[i][j];
}
}
void Floyd::output()
{
cout<<"Distances matrix: "<<endl;
for(unsigned int i = 0;i<number;i++)
{
for(unsigned int j = 0;j<number;j++)
{
cout.width(3);
cout<<distances[i][j]<<" ";
}
cout<<endl;
}
cout<<"Routes matrix: "<<endl;
for(unsigned int i = 0;i<number;i++)
{
for(unsigned int j = 0;j<number;j++)
{
cout.width(3);
cout<<routes[i][j]<<" ";
}
cout<<endl;
}
}
int Floyd::min(int a,int b)
{
return a<=b?a:b;
}
void Floyd::solve()
{
static int l=1;
if(l == number)
{
output();
}
else
{
for(unsigned int i = 0;i<number;i++)
for(unsigned int j = 0;j<number;j++)
{
if(i!=l && j!=l)
{
int lastDist = distances[i][j];
distances[i][j] = min(distances[i][j],(distances[i][l]+distances[l][j]));
if(distances[i][j]<lastDist)
{
routes[i][j] = l;
}
}
}
l++;
solve();
}
}