Advertisement
Guest User

ucs kecerdasan buatan

a guest
Oct 20th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import queue as Q
  2.  
  3. def uniform_cost_search(graph, start, end):
  4.  
  5. queue = Q.PriorityQueue()
  6. queue.put((0, [start]))
  7.  
  8. while not queue.empty():
  9. node = queue.get()
  10. current = node[1][len(node[1]) - 1]
  11.  
  12. if end in node[1]:
  13. print("Path found: " + str(node[1]) + ", Cost = " + str(node[0]))
  14. break
  15.  
  16. cost = node[0]
  17. for neighbor in graph[current]:
  18. temp = node[1][:]
  19. temp.append(neighbor)
  20. queue.put((cost + graph[current][neighbor], temp))
  21.  
  22. def inputGraph():
  23. lines = int( input() )
  24. graph = {}
  25.  
  26. for line in range(lines):
  27. line = input()
  28.  
  29. tokens = line.split()
  30. node = tokens[0]
  31. graph[node] = {}
  32.  
  33. for i in range(1, len(tokens) - 1, 2):
  34. graph[node][tokens[i]] = int(tokens[i + 1])
  35. return graph
  36.  
  37. def main():
  38. graph = inputGraph()
  39. uniform_cost_search(graph, 'Timisoara', 'Bucharest')
  40.  
  41. if __name__ == "__main__":
  42. main()
  43.  
  44. """masukkan ini di inputan:
  45. 13
  46. Arad Zerind 75 Timisoara 118 Sibiu 140
  47. Zerind Oradea 71 Arad 75
  48. Timisoara Arad 118 Lugoj 111
  49. Sibiu Arad 140 Oradea 151 Fagaras 99 RimnicuVilcea 80
  50. Oradea Zerind 71 Sibiu 151
  51. Lugoj Timisoara 111 Mehadia 70
  52. RimnicuVilcea Sibiu 80 Pitesti 97 Craiova 146
  53. Mehadia Lugoj 70 Dobreta 75
  54. Craiova Dobreta 120 RimnicuVilcea 146 Pitesti 138
  55. Pitesti RimnicuVilcea 97 Craiova 138 Bucharest 101
  56. Fagaras Sibiu 99 Bucharest 211
  57. Dobreta Mehadia 75 Craiova 120
  58. Bucharest Fagaras 211 Pitesti 101
  59. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement