Last active
October 11, 2018 12:47
-
-
Save Infl1ght/54960c499e24e17f4cf1db9c6f11b8ec to your computer and use it in GitHub Desktop.
Finding way in graph with the maximal sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Tested on Python 3.6.5 | |
def make_inversed_graph(graph): | |
inversed_graph = [{} for i in range(len(graph))] | |
for i, node in enumerate(graph): | |
for link in node: | |
inversed_graph[link][i] = node[link] | |
return inversed_graph | |
def find_max_path_for_node(graph, finish_node): | |
if len(graph[finish_node]) == 0: | |
return 0 | |
pathes = [] | |
for link in graph[finish_node]: | |
pathes.append(find_max_path_for_node(graph, link) + graph[finish_node][link]) | |
return max(pathes) | |
def find_max_path(graph, finish_node): | |
inversed_graph = make_inversed_graph(graph) | |
return find_max_path_for_node(inversed_graph, finish_node) | |
def test(): | |
a, b, c, d, e, f, g, h = range(8) | |
graph = [ | |
{b: 7, c: 9, f: 14}, | |
{c: 10, d: 15}, | |
{d: 11, f: 2}, | |
{e: 6}, | |
{f: 9}, | |
{}, | |
{h: 2}, | |
{g: 2}, | |
] | |
print(find_max_path(graph, f)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rus
Решение задачи поиска пути с максимальной суммой в графе. Граф обязательно должен быть направленным ациклическим, то есть он не может содержать в себе циклов. На вход подаётся граф в виде списка смежности и конечный узел, на выходе - максимальная сумма.
Задача решается с помощью динамического программирования.
Eng
Solving the problem of finding the path with the maximum sum in the graph. The graph must be directed and acyclic (DAG). The input is given by a finish node and a graph in the form of an adjacency list. The output is the maximum sum.
The problem is solved with dynamic programming.