def _test_shortest_paths(ds, algorithm): import pydatastructs.utils.misc_util as utils GraphNode = getattr(utils, "Adjacency" + ds + "GraphNode") vertices = [GraphNode('S'), GraphNode('C'), GraphNode('SLC'), GraphNode('SF'), GraphNode('D')] graph = Graph(*vertices) graph.add_edge('S', 'SLC', 2) graph.add_edge('C', 'S', 4) graph.add_edge('C', 'D', 2) graph.add_edge('SLC', 'C', 2) graph.add_edge('SLC', 'D', 3) graph.add_edge('SF', 'SLC', 2) graph.add_edge('SF', 'S', 2) graph.add_edge('D', 'SF', 3) dist, pred = shortest_paths(graph, algorithm, 'SLC') assert dist == {'S': 6, 'C': 2, 'SLC': 0, 'SF': 6, 'D': 3} assert pred == {'S': 'C', 'C': 'SLC', 'SLC': None, 'SF': 'D', 'D': 'SLC'} dist, pred = shortest_paths(graph, algorithm, 'SLC', 'SF') assert dist == 6 assert pred == {'S': 'C', 'C': 'SLC', 'SLC': None, 'SF': 'D', 'D': 'SLC'} graph.remove_edge('SLC', 'D') graph.add_edge('D', 'SLC', -10) assert raises(ValueError, lambda: shortest_paths(graph, 'bellman_ford', 'SLC'))
def _test_shortest_paths_negative_edges(ds, algorithm): import pydatastructs.utils.misc_util as utils GraphNode = getattr(utils, "Adjacency" + ds + "GraphNode") vertices = [ GraphNode('s'), GraphNode('a'), GraphNode('b'), GraphNode('c'), GraphNode('d') ] graph = Graph(*vertices) graph.add_edge('s', 'a', 3) graph.add_edge('s', 'b', 2) graph.add_edge('a', 'c', 1) graph.add_edge('b', 'd', 1) graph.add_edge('b', 'a', -2) graph.add_edge('c', 'd', 1) dist, pred = shortest_paths(graph, algorithm, 's') assert dist == {'s': 0, 'a': 0, 'b': 2, 'c': 1, 'd': 2} assert pred == {'s': None, 'a': 'b', 'b': 's', 'c': 'a', 'd': 'c'} dist, pred = shortest_paths(graph, algorithm, 's', 'd') assert dist == 2 assert pred == {'s': None, 'a': 'b', 'b': 's', 'c': 'a', 'd': 'c'}
def _test_shortest_paths_negative_edges(ds, algorithm): import pydatastructs.utils.misc_util as utils GraphNode = getattr(utils, "Adjacency" + ds + "GraphNode") vertices = [ GraphNode('1'), GraphNode('2'), GraphNode('3'), GraphNode('4') ] graph = Graph(*vertices) graph.add_edge('1', '3', -2) graph.add_edge('2', '1', 4) graph.add_edge('2', '3', 3) graph.add_edge('3', '4', 2) graph.add_edge('4', '2', -1) dist, next_v = shortest_paths(graph, algorithm, 's') assert dist == { '1': { '3': -2, '1': 0, '4': 0, '2': -1 }, '2': { '1': 4, '3': 2, '2': 0, '4': 4 }, '3': { '4': 2, '3': 0, '1': 5, '2': 1 }, '4': { '2': -1, '4': 0, '1': 3, '3': 1 } } assert next_v == { '1': { '3': '1', '1': '1', '4': None, '2': None }, '2': { '1': '2', '3': None, '2': '2', '4': None }, '3': { '4': '3', '3': '3', '1': None, '2': None }, '4': { '2': '4', '4': '4', '1': None, '3': None } }