[英]PostgreSQL - Shortest Path
我有一個網格表,其中存儲一個起點和一個目的地點。 看起來像這樣:
src | dest | cost
-------+-------+------
{1,1} | {1,2} | 1
{1,1} | {2,1} | 1
{1,2} | {1,1} | 1
{1,2} | {1,3} | 1
{1,2} | {2,2} | 1
...
{4,5} | {5,5} | 1
我想從我的起點開始,然后到它的鄰居之一,再到他的鄰居,依此類推。
到目前為止,我有這段代碼(計數器只是為了確保我不會陷入無限循環中):
WITH RECURSIVE
init (here, there, cost_to_here, counter, path ) AS (
SELECT g.src, g.dest, 0.0, 1, array[g.src, g.dest] -- SourcePoint with a cost of 0 src -> src
FROM grid AS g
WHERE g.src = '{1,1}'
UNION ALL
(WITH init(here, there, cost_to_here, counter, path) AS (TABLE init) -- Reference the working Table once
SELECT g.src, g.dest, i1.cost_to_here + g.cost, i1.counter + 1, i1.path || array[g.dest]
FROM grid AS g, init AS i1
WHERE g.src = i1.there
AND NOT g.dest = ANY(i1.path)
AND (i1.here) IN (select i2.here
from init as i2)
and i1.counter < 7
)
)
table init;
我從src點{1,1}
並訪問它的鄰居。 由於我不想回到已經訪問過的地點,因此請檢查是否已經訪問了下一個地點。
這是代碼的作用:
here | there | cost_to_here | counter | path
-------+-------+--------------+---------+--------------------------------------
{1,1} | {1,2} | 0.0 | 1 | {"{1,1}","{1,2}"}
{1,1} | {2,1} | 0.0 | 1 | {"{1,1}","{2,1}"}
{1,2} | {1,3} | 1.0 | 2 | {"{1,1}","{1,2}","{1,3}"}
{1,2} | {2,2} | 1.0 | 2 | {"{1,1}","{1,2}","{2,2}"}
{2,1} | {2,2} | 1.0 | 2 | {"{1,1}","{2,1}","{2,2}"}
...
{1,2} | {1,3} | 3.0 | 4 | {"{1,1}","{2,1}","{2,2}","{1,2}","{1,3}"}
{2,3} | {1,3} | 3.0 | 4 | {"{1,1}","{1,2}","{2,2}","{2,3}","{1,3}"}
如您所見,它為我生成了通往{1,3}
不同路徑。 我如何才能保持最好的狀態?
但是我只想保持最好的道路。 我該如何處理?
然后,保持最短的一個。 像這樣:
select distinct on (src, dest) i.*
from init 8
order by src, dest, cost_to_here;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.