|
5 | 5 | sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
6 | 6 | from search import *
|
7 | 7 | from search import breadth_first_tree_search as bfts, depth_first_tree_search as dfts, \
|
8 |
| - depth_first_graph_search as dfgs, breadth_first_search as bfs, uniform_cost_search as ucs |
| 8 | + depth_first_graph_search as dfgs, breadth_first_search as bfs, uniform_cost_search as ucs, \ |
| 9 | + astar_search as asts |
9 | 10 | from utils import Stack, FIFOQueue, PriorityQueue
|
10 | 11 | from copy import deepcopy
|
11 | 12 |
|
@@ -512,6 +513,14 @@ def uniform_cost_search(problem):
|
512 | 513 | return best_first_graph_search(problem, lambda node: node.path_cost)
|
513 | 514 |
|
514 | 515 |
|
| 516 | +def astar_search(problem, h=None): |
| 517 | + """A* search is best-first graph search with f(n) = g(n)+h(n). |
| 518 | + You need to specify the h function when you call astar_search, or |
| 519 | + else in your Problem subclass.""" |
| 520 | + h = memoize(h or problem.h, 'h') |
| 521 | + return best_first_graph_search(problem, lambda n: n.path_cost + h(n)) |
| 522 | + |
| 523 | + |
515 | 524 | # TODO:
|
516 | 525 | # Remove redundant code.
|
517 | 526 | # Make the interchangbility work between various algorithms at each step.
|
@@ -561,6 +570,14 @@ def on_click():
|
561 | 570 | display_final(final_path)
|
562 | 571 | next_button.config(state="disabled")
|
563 | 572 | counter += 1
|
| 573 | + elif "A* - Search" == algo.get(): |
| 574 | + node = astar_search(romania_problem) |
| 575 | + if node is not None: |
| 576 | + final_path = asts(romania_problem).solution() |
| 577 | + final_path.append(start.get()) |
| 578 | + display_final(final_path) |
| 579 | + next_button.config(state="disabled") |
| 580 | + counter += 1 |
564 | 581 |
|
565 | 582 |
|
566 | 583 | def reset_map():
|
@@ -589,7 +606,7 @@ def main():
|
589 | 606 | root,
|
590 | 607 | algo, "Breadth-First Tree Search", "Depth-First Tree Search",
|
591 | 608 | "Breadth-First Search", "Depth-First Graph Search",
|
592 |
| - "Uniform Cost Search") |
| 609 | + "Uniform Cost Search", "A* - Search") |
593 | 610 | Label(root, text="\n Search Algorithm").pack()
|
594 | 611 | algorithm_menu.pack()
|
595 | 612 | Label(root, text="\n Start City").pack()
|
|
0 commit comments