2019-02-15 10:47:50 +00:00
|
|
|
from collections import deque
|
|
|
|
|
|
|
|
from cfg import config
|
2019-02-02 15:07:19 +00:00
|
|
|
|
|
|
|
def prepare_dijkstra(connection):
|
|
|
|
cursor = connection.cursor()
|
|
|
|
cursor.execute('''INSERT OR IGNORE INTO dijkstra_helper(name)
|
|
|
|
SELECT destination FROM links
|
|
|
|
''')
|
|
|
|
|
2019-02-15 10:47:50 +00:00
|
|
|
if(config["use_sqlite"]):
|
|
|
|
cursor.execute("UPDATE dijkstra_helper SET value=1e1000")
|
|
|
|
else:
|
|
|
|
cursor.execute("UPDATE dijkstra_helper SET value=2147483647")
|
2019-02-02 15:07:19 +00:00
|
|
|
connection.commit()
|
|
|
|
|
|
|
|
def dijkstra_one(title, value, connection):
|
|
|
|
cursor = connection.cursor()
|
|
|
|
if(isinstance(title, tuple)):
|
|
|
|
# Idk why this happens.
|
|
|
|
title = title[0]
|
|
|
|
cursor.execute('''SELECT name
|
|
|
|
FROM dijkstra_helper
|
|
|
|
LEFT JOIN links ON links.destination=dijkstra_helper.name
|
|
|
|
WHERE links.source=:title
|
|
|
|
AND dijkstra_helper.value>:value''', {"title": title, "value": value + 1})
|
|
|
|
# This is the list of nodes that have to be updated
|
|
|
|
result = cursor.fetchall()
|
|
|
|
|
|
|
|
cursor.execute('''UPDATE dijkstra_helper
|
|
|
|
SET value=:value
|
|
|
|
WHERE name IN (
|
|
|
|
SELECT destination
|
|
|
|
FROM links
|
|
|
|
WHERE source=:title)
|
|
|
|
AND dijkstra_helper.value>:value''', {"value": value + 1, "title": title})
|
|
|
|
connection.commit()
|
|
|
|
return result
|
|
|
|
|
|
|
|
def recursive_dijkstra(titles, value, connection):
|
|
|
|
if(not titles):
|
|
|
|
return
|
|
|
|
|
2019-02-15 10:47:50 +00:00
|
|
|
todos = deque()
|
2019-02-02 15:07:19 +00:00
|
|
|
for title in titles:
|
2019-02-15 10:47:50 +00:00
|
|
|
todos.extend(dijkstra_one(title, value, connection))
|
|
|
|
|
|
|
|
recursive_dijkstra(todos, value + 1, connection)
|
2019-02-02 15:07:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
def dijkstra(title, connection):
|
|
|
|
cursor = connection.cursor()
|
2019-02-15 11:46:32 +00:00
|
|
|
cursor.execute("UPDATE dijkstra_helper SET value=0 WHERE name=%s", (title,))
|
2019-02-02 15:07:19 +00:00
|
|
|
|
|
|
|
todos = dijkstra_one(title, 1, connection)
|
|
|
|
recursive_dijkstra(todos, 2, connection)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|