Files
KI/main.py
2025-04-15 17:24:18 +02:00

83 lines
3.1 KiB
Python

from graph import Graph, Node, Queue
from utils import getNode
# directed and weighted digraph
romania = Graph( ['Or', 'Ne', 'Ze', 'Ia', 'Ar', 'Si', 'Fa',
'Va', 'Ri', 'Ti', 'Lu', 'Pi', 'Ur', 'Hi',
'Me', 'Bu', 'Dr', 'Ef', 'Cr', 'Gi'],
[
('Or', 'Ze', 71), ('Or', 'Si', 151),
('Ne', 'Ia', 87), ('Ze', 'Ar', 75),
('Ia', 'Va', 92), ('Ar', 'Si', 140),
('Ar', 'Ti', 118), ('Si', 'Fa', 99),
('Si', 'Ri', 80), ('Fa', 'Bu', 211),
('Va', 'Ur', 142), ('Ri', 'Pi', 97),
('Ri', 'Cr', 146), ('Ti', 'Lu', 111),
('Lu', 'Me', 70), ('Me', 'Dr', 75),
('Dr', 'Cr', 120), ('Cr', 'Pi', 138),
('Pi', 'Bu', 101), ('Bu', 'Gi', 90),
('Bu', 'Ur', 85), ('Ur', 'Hi', 98),
('Hi', 'Ef', 86)
] )
def search(graph, queue, start_node_name, target_node_name):
visited_nodes = [] # Nodes which have been visited
path = []
start_node = getNode(start_node_name, graph.nodes)
target_node = getNode(target_node_name, graph.nodes)
start_node.value = 0
queue.push(start_node)
while not queue.empty():
current_node = queue.pop()
visited_nodes.append(current_node.name)
if not current_node == target_node:
for edge in current_node.edges:
neighbor = edge.end
condition = not visited_nodes.__contains__(neighbor.name)
new_cost = current_node.value + edge.value
# UCS
if queue.type == 'PRIO':
condition = not visited_nodes.__contains__(neighbor.name) and new_cost < neighbor.value
# works with digraph, because current_node is marked at this point, a cycle is not possible
if condition:
neighbor.parent = current_node
neighbor.value = new_cost
queue.push(neighbor)
else:
path.append(current_node.name)
while not current_node == start_node:
current_node = current_node.parent
path.insert(0, current_node.name)
if path.__len__() == 0:
print('zwischen ' + start_node_name + ' und ' + target_node_name + ' konnte kein Pfad gefunden werden')
else:
print('From ' + start_node_name + ' to ' + target_node_name + ': ')
print('Path: ' + path.__str__().format())
print('Cost: ' + target_node.value.__str__())
def bfs(graph, start_node_name, target_node_name):
search(graph,Queue('FIFO'),start_node_name, target_node_name)
def dfs(graph, start_node_name, target_node_name):
search(graph,Queue('LIFO'),start_node_name, target_node_name)
def utc(graph, start_node_name, target_node_name):
search(graph,Queue('PRIO'),start_node_name, target_node_name)
def main():
bfs(romania, 'Ti', 'Bu')
dfs(romania, 'Ti', 'Bu')
utc(romania, 'Or', 'Si')
if __name__ == "__main__":
main()