How to calculate the diameter of the network

I have data stored in mysql and PHP relational database. I have a table called "rel" that has two fields:

from_node  |  to_node
=====================
1               2
1               3
2               3

etc.

How to calculate the network diameter of the network. I know this is the longest or shortest path between any two pairs, but how can I calculate it? Is there any PHP script or function that can help me?

+3
source share
6 answers

Assuming you have a connected graph (otherwise the maximum distance is infinite), and all your node points are numbers ....

(, , ) (from_node, to_node, 1). , from_node to_node

CREATE TABLE hops (
    from_node int not null,
    to_node int not null,
    distance int not null default 0,
    primary key (from_node, to_node, distance)
)

-- first load:
INSERT INTO hops (from_node, to_node)
SELECT from_node, to_node FROM rel;

-- iterative step
INSERT INTO hops (from_node, to_node, distance)
SELECT a.from_node, b.to_node, min(a.distance+b.distance)
FROM hops a, hops b
WHERE a.to_node = b.from_node
  AND a.from_node <> b.from_node  -- not self
  AND a.to_node <> b.to_node      -- still not self
  AND a.from_node <> b.from_node  -- no loops
  AND NOT EXISTS (                -- avoid duplicates
          SELECT * FROM hops c
          WHERE c.from_node = a.from_node
            AND c.to_node = b.to_node
            AND c.distance = a.distance+b.distance)
GROUP BY a.from_node, b.to_node

, . , .

EDIT: , 1.

+1

, node node. , 1.

- , :

n=1, n = 2, n = 3, ... n

(n + 1)/3.

, N K-, logN/LogK

: , .

n1 - n2 - n3
(n+1)/3 = 4/3

n1-n2 = 1 hop
n2 - n3 = 1 hop
n1- n2 - n3 = 2 hops
(1+1+2)/3 = 4/3
0

. (), . , . , , . ( , , .) , /, , .

( , ), /. , , PHP. (, , - interop.)

, .

0

, , . , PHP. , PHP.

, , . , .

, , / .

0

- . , - BFS DFS? , .

0

:

    • colum distance
    • -1
    • node (, )
    • 1
    • , -1
      • UPDATE table SET distance=:i+1 WHERE from_node IN (SELECT to_node FROM table WHERE distance=:i)
    • node, () -
    • -1
    • remebered node 1

- /.

0

Source: https://habr.com/ru/post/1708014/


All Articles