r/dailyprogrammer • u/jnazario 2 0 • May 11 '16
[2016-05-11] Challenge #266 [Intermediate] Graph Radius and Diameter
This week I'll be posting a series of challenges on graph theory. I picked a series of challenges that can help introduce you to the concepts and terminology, I hope you find it interesting and useful.
Description
Graph theory has a relatively straightforward way to calculate the size of a graph, using a few definitions:
- The eccentricity ecc(v) of vertex (aka node) v in graph G is the greatest distance from v to any other node.
- The radius rad(G) of G is the value of the smallest eccentricity.
- The diameter diam(G) of G is the value of the greatest eccentricity.
- The center of G is the set of nodes v such that ecc(v)=rad(G)
So, given a graph, we can calculate its size.
Input Description
You'll be given a single integer on a line telling you how many lines to read, then a list of n lines telling you nodes of a directed graph as a pair of integers. Each integer pair is the source and destination of an edge. The node IDs will be stable. Example:
3
1 2
1 3
2 1Output Description
Your program should emit the radius and diameter of the graph. Example:
Radius: 1
Diameter: 2Challenge Input
147
10 2
28 2
2 10
2 4
2 29
2 15
23 24
23 29
15 29
15 14
15 34
7 4
7 24
14 2
14 7
14 29
14 11
14 9
14 15
34 15
34 14
34 29
34 24
34 11
34 33
34 20
29 23
29 7
29 2
29 18
29 27
29 4
29 13
29 24
29 11
29 20
29 9
29 34
29 14
29 15
18 27
18 13
18 11
18 29
27 18
27 4
27 24
4 2
4 27
4 13
4 35
4 24
4 20
4 29
13 18
13 16
13 30
13 20
13 29
13 4
13 2
24 4
24 30
24 5
24 19
24 21
24 20
24 11
24 29
24 7
11 18
11 24
11 30
11 33
11 20
11 34
11 14
20 29
20 11
20 4
20 24
20 13
20 33
20 21
20 26
20 22
20 34
22 34
22 11
22 20
9 29
9 20
21 9
21 20
21 19
21 6
33 24
33 35
33 20
33 34
33 14
33 11
35 33
35 4
35 30
35 16
35 19
35 12
35 26
30 13
30 19
30 35
30 11
30 24
16 36
16 19
16 35
16 13
36 16
31 16
31 19
5 19
19 30
19 16
19 5
19 35
19 33
19 24
12 33
12 35
12 3
12 26
26 21
26 35
6 21
6 19
1 6
8 3
8 6
3 8
3 6
3 12
3 35
33 29
29 33
14 33
29 21Challenge Output
Radius: 3
Diameter: 6** NOTE ** I had mistakenly computed this for an undirected graph which gave the wrong diameter. It should be 6.
2
u/bearific May 11 '16 edited May 12 '16
Python 3, I use the Floyd-Warshall algorithm to find all shortest paths, and then pick the longest path of each node as the eccentricity. I don't think this can be done faster than O( V3 )?
I used the graph class from an existing graph isomorphism project, I only use a list of edge tuples and the node count so I won't include the graph class.
7
u/jnd-au 0 1 May 12 '16 edited May 14 '16
It looks like our solutions can be classified as either matrix-based (esp. Floyd-Warshall) or breadth-first-search (BFS). Several good ones here. Typically, Matrices scale O(n3) while BFS scales O(n) for this task. An eclectic mix of languages but we could do with a few more :)
Solution | Language | Approach | Time Scaling*
01 bearific | Python 3 | Floyd-Warshall | O(n3) 02 Godspiral | J | | 03 fish_on_dude | Fortran | AdjMatrixn | O(n3) 04 jnd-au | Scala | BFS Hash | O(n) 05 skeeto | C | BFS Queue | O(n) 06 MichaelPenn | Python 3 | Floyd-Warshall | O(n3) 07 The_Jare | Rust | Floyd-Warshall | O(n3) 08 fvandepitte | Haskell | BFS AdjMatrix | O(n) 09 Gobbedyret | Python3 | Matrix | O(n3)† 10 thorwing | Java | BFS | 11 Tobask | Python 2 | BFS | O(n2) 12 EPYJAO | Go | BFS | 13 FrankRuben27 | Common Lisp | BFS Queue | 14 voice-of-hermes | Python3 | Floyd-Warshall | O(n3) 15 wizao | Haskell | Floyd-Warshall | Parallelised 16 krelix | Rust | | 17 FlammableMarshmallow | C++ | | 18 trinity37185 | Java | |
* Please note, n here is a generic scaling factor, not N the number of paths. Algorithms may scale on inputs like the number of nodes (vertices V) and/or the number of ordered pairs (edges E), or on properties like N the number of all possible paths. Different algorithms are sensitive to different things, so there are lots of possibilities for n, like V+E, or V×E, or max(V, E), N, etc. I considered the ‘average’ case V = E = n, so either of those input terms can dominate.
† In response to criticism from voice-of-hermes, I have been verifying the theoretical scalings with benchmarks too. So far they hold up. The only discrepancy is Gobbedyret’s, which performed better like O(n2) over the first order of magnitude at least.
1
u/fvandepitte 0 0 May 11 '16
/u/jnazario, am I correct that this would be the matrix and degrees of the first input?
1
u/moeghoeg May 11 '16
What does it mean that "the node ID:s will be stable"?
Can we assume that the nodes are numbered so that they form a range without gaps, (i.e. 1,2,3,4 and not for example 1,2,4,5)?
3
u/[deleted] May 11 '16 edited May 12 '16
Fortran .... just multiply the adjacency matrix by itself N times; non-zero entries in An indicate there's a n-step path to get from i to j.
EDIT - moved the source code to ideone.com: here
switching back and forth between "undirected" (as I assumed) and "directed" gives different answers, as discovered multiple times in this thread by other people.
undirected graph
directed graph
1
u/jnd-au 0 1 May 11 '16
/u/jnazario:
There are 147 lines!
2
u/skeeto -9 8 May 11 '16
C, using a bitarray adjacency graph and a hastily-made queue to compute distances (BFS). I get 6 for the challenge input diameter.
2
u/wizao 1 0 May 13 '16 edited May 13 '16
Haskell:
I implemented a parallel version of Floyd-Warshall. I wanted it to be type safe and fast (why else make it parallel), so there is a lot of boilerplate making
Unbox/Eltinstances of various wrappers. It solves the challenges instantaneously, so I had to generate bigger input. I created a fully connected 1000x1000 graph to compare the sequential vs parallel versions. The sequential one finished in 42 seconds while the parallel one finished in 13 seconds, about 3.3x faster including parsing. I should get another 40% speedup if I can figure out how to get llvm working.This code is based off code from the book Parallel and Concurrent Programming in Haskell. It's free to read online and even has 3 different Floyd-Warshall implementations: a
Parmonad (adj list w/ futures), Repa library (adj matrix w/ data parallel), and Accelerate library (adj matrix w/ CUDA or OpenCL). My implementation follows the Repa version. I haven't got to implement the accelerate version, but the book's reports it is 3.5x faster than the llvm repa version!2
u/[deleted] May 13 '16 edited Feb 25 '24
I enjoy the sound of rain.
1
u/Godspiral 3 3 May 11 '16
in J, maybe I don't know what distance means, but the list of eccentricities are:
the largest and smallest are:
32 5
node 1 only has one link (to node 6)... so its max distance is 5?
node 3 has many links, but one is to node 35, so its max distance is 32?
1
u/jnd-au 0 1 May 11 '16 edited May 13 '16
Scala naïve but fast BFS approach:
Challenge output:
The reason for diameter 6 is that there are 9 paths with that many distances, e.g. (1, 6, 19, 35, 12, 3, 8).
But the official answer is 5. Have I misunderstood? Perhaps there is a shorter path from 1 -> 8 that I have overlooked? Please help!I was correct. Solution:Edit:
extendPathsloop debugging:Edit2: If I treat it as an undirected graph (uncomment
+ ainoutwardConnections), then I get 5 for the answer. In this situation, 1 -> 8 changes to (1, 6, 8) thus reducing the diameter to 5 with paths like 8 -> 10 (8, 3, 35, 4, 2, 10).Edit3: Inspired by wizao, here’s a parallelised BFS solution. Just replace
val shortestPathLengths = ...with this:1
u/The_Jare May 12 '16 edited May 12 '16
Rust:
Output:
1
u/SpaceJamSpaceJam May 12 '16
i was stuck on this all day because i thought distance meant the longest path from one node to another with no loops.
1
u/fvandepitte 0 0 May 12 '16
Haskell
Feedback is welcome, I need to cache met eccentricity results to make it more effecient.
1
u/thorwing May 12 '16
I have some questions.
Distance is basically the longest route possible from node N to any of its directional children right?
This should have diameter 3 and radius 1 right?
Do closed loops exist in these kind of graphs? If so, do they have eccentricity = 0, loopsize or infinity?
1
u/Gobbedyret 1 0 May 12 '16 edited May 13 '16
Python 3.5 without bonus
This is adjecency matrix based. Essentially I matrix multiply the adjecency matrix with itself to compute which nodes are reached in N steps from each other node. I also keep another matrix to keep track of which nodes has already been reached, so that it only considers the shortest path.
It scales O(n3) x D, where D is the graph's diameter, but it's very fast. It takes my laptop 2.6 ms to compute the challenge input. For a fully connected graph with 1000 nodes, it takes 4.2 seconds, almost exactly half of which is spent parsing the one million line input.
On a related node, I remain unconvinced that it's possile to solve this faster than O(n3)
This code is just the business logic condensed for the sake of this challenge. It doesn't check for correct inputs or accept nodes with arbitrary numbering, for example.
1
u/thorwing May 12 '16 edited May 13 '16
JAVA
With my questions answered by /u/jnd-au, I could begin with the challenge. For most of these programming challenges I like to come up with my own algorithm (instead of looking them up), because I'm confident I can think of something fast. Hopefully this fullfills the constraint of fastness :)
The algorithm keeps track op the direct parents of every node and the list of shortest paths to any child node. When a line is created from Node n1 to Node n2, the map of shortest paths from n2 (M) will be presented to n1. n1 then filters M, based on if shorter paths are available to known nodes or if the known was previously unknown to n1. if M has any updates at all, n1 will update it's own map and the parents of n1 update their paths based on M. This will continue until all updateable values are updated.
Edit: I've taken a look at it's complexity and with n = lines:
best case: O(n), every line added is a parent of all known lines, meaning no pass-on updates.
worst case: O(n(n+1)/2), every line added is a child of all known lines and every node has one line, meaning all previously known nodes need to be updated.
1
u/Tobask May 12 '16 edited May 13 '16
Since distance here simply means # of edges between nodes, this can be solved with a standard BFS with a run time linear in the size of the adjacency-list, or O(V + E). Python (2) implementation:
1
u/[deleted] May 12 '16
Go
This is a BFS search on each disjoint subgraph of the input. The runtime is O(V*(V + E)) ~ O(V * (V + V2 )) ~ O(V3 ) since it does a breadth first search over each vertex.
Results:
1
u/FrankRuben27 0 1 May 12 '16 edited May 12 '16
One more language added: Common Lisp; approach is BFS Queue for AdjMatrix:
1
u/voice-of-hermes May 13 '16
1
u/FlammableMarshmallow May 13 '16 edited May 13 '16
C++
I'm not sure if this is even a correct solution.
EDIT: Added
Graph::center1
u/trinity37185 May 13 '16
Solution in Java.
https://gist.github.com/trideon3/6a77ef8ffd9a9c9c18a189b75bdf5eec
Took me some time to figure out that you had to implement the HashCode function for the HashedSet to work correctly.
Also should'nt the eccentricity of 3 in the first example be Infinite since its disconnected from the rest of the graph? Would'nt that mean that the diameter is Infinite as well? That's atleast the impression i got from wolfram.
1
u/jsco May 16 '16
Python 3
1
u/weekendblues May 20 '16
My very late solution in Java, using BFS.
1
u/[deleted] May 28 '16 edited May 28 '16
Wrote a working solution in C++ using the Floyd-Warshall algorithm. Using the algorithm, I find the eccentricity for each vertex and then I pick the greatest eccentricity out of all of the verticies and make that the diameter. The solution reads from a simple text file named "datafile.txt" with the test input int it. The solution works with the challenge input as well as the non-challenge input.
1
u/EtDecius Jun 02 '16
C++: Implemented using BFS, data stored in a map and vectors
Output:
1
u/lumos510 Jun 04 '16
Here is my Java implementation using FLoyd Warshall Algorithm.
1
u/[deleted] Jun 06 '16
Golang