-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequential.c
129 lines (110 loc) · 2.05 KB
/
sequential.c
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "config.h"
void showDistances(int matrix[], int n);
void populateMatrix(int* matrix, int n, int density);
void floydWarshall(int* matrix, int n);
int main(int argc, char** argv)
{
uint n, density;
if(argc <= 2)
{
n = DEFAULT;
density = 100;
}
else
{
n = atoi(argv[1]);
density = atoi(argv[2]);
}
int* matrix;
matrix = (int*) malloc(n * n *sizeof(int));
populateMatrix(matrix, n, density);
printf("*** Adjacency matrix:\n");
showDistances(matrix, n);
struct timespec start, end;
long long accum;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
floydWarshall(matrix, n);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
accum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
printf("*** The solution is:\n");
showDistances(matrix, n);
printf("[SEQUENTIAL] Total elapsed time %lld ns\n", accum);
free(matrix);
return 0;
}
void floydWarshall(int* matrix, int n)
{
uint i, j, k;
for(k = 0; k < n; k++)
{
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
int newPath = matrix[i * n + k] + matrix[k * n + j];
if (matrix[i * n + j] > newPath)
{
matrix[i * n + j] = newPath;
}
}
}
}
}
void showDistances(int matrix[], int n)
{
if(PRINTABLE)
{
int i, j;
printf(" ");
for(i = 0; i < n; i++)
{
printf("[%d] ", i);
}
printf("\n");
for(i = 0; i < n; i++) {
printf("[%d]", i);
for(j = 0; j < n; j++)
{
if(matrix[i * n + j] == INF)
{
printf(" inf");
}
else
{
printf("%5d", matrix[i * n + j]);
}
}
printf("\n");
}
printf("\n");
}
}
void populateMatrix(int *matrix, int n, int density)
{
uint i, j, value;
srand(42);
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++){
if(i == j)
{
matrix[i*n+j] = 0;
}
else
{
value = 1 + rand() % MAX;
if(value > density)
{
matrix[i*n+j] = INF;
}
else
{
matrix[i*n+j] = value;
}
}
}
}
}