File: apsp.5c

package info (click to toggle)
nickle 2.107
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 3,756 kB
  • sloc: ansic: 27,954; yacc: 1,874; lex: 954; sh: 204; makefile: 13; lisp: 1
file content (53 lines) | stat: -rw-r--r-- 1,317 bytes parent folder | download | duplicates (4)
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
 * All-Pairs Shortest Path Computation
 * using Floyd-Warshall O(n**3) method
 *  CLR 2nd ed p. 632
 * Copyright © 2004 Bart Massey.
 * All Rights Reserved.  See the file COPYING in this directory
 * for licensing information.
 */
namespace APSP {
    public typedef real distance;

    public typedef struct {
	distance dist;
	int first_hop;
    } shortest_path;

    public shortest_path[*,*]
    compute_paths(distance[*,*] adjacencies) {
	int[*] ns = dims(adjacencies);
	assert(dim(ns) == 2 && ns[0] == ns[1],
	       "ill-conditioned adjacencies");
	int n = ns[0];
	/* set things up */
	shortest_path[n,n] path =
	  {{{.dist = -1, .first_hop = -1}, ...},...};
	for (int i = 0; i < n; i++) {
	    for (int j = 0; j < n; j++) {
		if (i != j && adjacencies[i,j] >= 0) {
		    path[i,j].dist = adjacencies[i,j];
		    path[i,j].first_hop = j;
		}
	    }
	}
	/* do the computation */
	for (int k = 0; k < n; k++) {
	    for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
		    if (i == j)
			continue;
		    real dik = path[i,k].dist;
		    real dkj = path[k,j].dist;
		    if (dik < 0 || dkj < 0)
			continue;
		    real dij = path[i,j].dist;
		    if (dij < 0 || dik + dkj < dij) {
			path[i,j].dist = dik + dkj;
			path[i,j].first_hop = path[i,k].first_hop;
		    }
		}
	    }
	}
	return path;
    }
}