{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6091e7e0",
   "metadata": {},
   "source": [
    "# 🌟 A* search in Python\n",
    "\n",
    "In the chapter [Heuristic Search](https://ai.kuleuven.be/aivooriedereen/en/heuristic-search) you saw A\\* find the cheapest route in the demos. This notebook shows what that looks like in code: one short Python function that you can copy and use as a starting point for your own search problems.\n",
    "\n",
    "You will use that same function twice:\n",
    "\n",
    "1. 🔤 to solve a word ladder: turn one word into another, one letter at a time;\n",
    "2. 🗺️ to plan a real route between two places, with map data from OpenStreetMap.\n",
    "\n",
    "**Prior knowledge**: the chapters [Search Algorithms](https://ai.kuleuven.be/aivooriedereen/en/search) and [Heuristic Search](https://ai.kuleuven.be/aivooriedereen/en/heuristic-search). You don't need any programming experience: you can run the whole notebook without changing a single line.\n",
    "\n",
    "**Estimated time**: about 30 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/a-star-search](https://ai.kuleuven.be/aivooriedereen/en/notebook/a-star-search), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1l_BnrMiX9Yr-Md-ykKI9byND01HIPRhN?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdf54a63",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **Run the cells in order, from top to bottom**, because a cell uses what the cells above it made. Does something behave strangely? Choose *Runtime → Restart session* and run everything again from the top.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/a-star-search.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc679fa8",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, dictionaries, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `word = \"sleep\"` | A piece of text, a **string**. It works much like a list of letters: positions start at 0, so `word[0]` is `\"s\"`, `word[:2]` gives the letters before position 2 (`\"sl\"`) and `word[3:]` the letters from position 3 on (`\"ep\"`). `for letter in \"abc\":` runs through its letters, `+` glues strings together, and `text.split()` cuts a text into a list of words. |\n",
    "| `{\"sleep\", \"dream\"}` | A **set**: a collection without order or duplicates. `\"sleep\" in words` checks in one go whether a word is in it, however big the set is, and `visited.add(state)` adds an item. `set()` is an empty set. |\n",
    "| `while x < 100:` | Repeats the indented lines below it as long as the condition is true. `while frontier:` repeats as long as the list `frontier` isn't empty. |\n",
    "| `continue` | Inside a loop: skip the rest of this round and go on with the next item. |\n",
    "| `None` | \"Nothing\": what a function gives back when it has no answer. `if path is None:` checks for it. |\n",
    "| `return path, cost` | Gives back two values at once; `path, cost = a_star(...)` catches them in two variables. |\n",
    "| `a_star(start, goal, one_letter_changes, letters_to_change)` | A function can be an input of another function. Pass its name **without parentheses**: `a_star` calls `one_letter_changes(...)` itself, as often as it needs. |\n",
    "| `with open(\"data/words.txt\") as file:` | Opens a file; inside the indented block, `file.read()` gives its whole text. `os.path.exists(\"data/words.txt\")` tells whether that file exists. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8e0ee63",
   "metadata": {},
   "source": [
    "## 🌟 The A\\* algorithm\n",
    "\n",
    "In the chapter, A\\* keeps a **frontier**: the paths it may still extend, sorted by their f-value\n",
    "\n",
    "$$f(n) = g(n) + h(n)$$\n",
    "\n",
    "where $g(n)$ is the cost of the path so far and $h(n)$ the heuristic: an estimate of the remaining cost to the goal. In every step, A\\* takes the path with the lowest $f$ out of the frontier and extends it with all neighboring states. As soon as it takes a path to the goal out of the frontier, that path is the cheapest one, provided the heuristic never estimates too high.\n",
    "\n",
    "The function `a_star` below does exactly that. You give it four things:\n",
    "\n",
    "- `start`: the start state;\n",
    "- `goal`: the goal state;\n",
    "- `neighbors`: a function that gives, for a state, all states you can reach from it with one action, each with the cost of that action;\n",
    "- `heuristic`: a function that estimates the remaining cost from a state to the goal.\n",
    "\n",
    "It gives back the path it found (a list of states, from start to goal) and the total cost of that path.\n",
    "\n",
    "For the frontier, the code uses `heapq`, Python's [priority queue](https://ai.kuleuven.be/aivooriedereen/en/heuristic-search#priority-queue): `heappush` puts a path in the frontier, and `heappop` takes out the path with the lowest $f$.\n",
    "\n",
    "Run the code with Shift+Enter so the function is defined in this notebook from now on."
   ]
  },
  {
   "cell_type": "code",
   "id": "cdf24270",
   "metadata": {},
   "source": [
    "import heapq  # Python's priority queue\n",
    "\n",
    "\n",
    "def a_star(start, goal, neighbors, heuristic):\n",
    "    \"\"\"\n",
    "    Find the cheapest path from start to goal.\n",
    "    Gives back the path (a list of states) and its total cost.\n",
    "    \"\"\"\n",
    "    # The frontier holds paths as (f, g, path); heapq gives back the lowest f first.\n",
    "    frontier = [(heuristic(start, goal), 0, [start])]  # start with one path, containing only the start state\n",
    "    visited = set()  # the states whose neighbors we already added\n",
    "\n",
    "    while frontier:  # as long as there are paths left in the frontier\n",
    "        f, g, path = heapq.heappop(frontier)  # take out the path with the lowest f\n",
    "        state = path[-1]  # the last state on that path\n",
    "\n",
    "        if state == goal:\n",
    "            return path, g  # the cheapest path to the goal!\n",
    "        if state in visited:\n",
    "            continue  # we already reached this state in a cheaper way: skip this path\n",
    "        visited.add(state)\n",
    "\n",
    "        for next_state, cost in neighbors(state):\n",
    "            if next_state not in visited:\n",
    "                new_g = g + cost  # the cost of the path, one step further\n",
    "                new_f = new_g + heuristic(next_state, goal)  # f = g + h\n",
    "                heapq.heappush(frontier, (new_f, new_g, path + [next_state]))\n",
    "\n",
    "    return None, None  # the frontier is empty: there is no path to the goal"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5551e22a",
   "metadata": {},
   "source": [
    "Running this cell shows nothing: it only *defines* the function. From now on, you can use `a_star` in every cell below it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e936e68",
   "metadata": {},
   "source": [
    "## 🔤 Example: a word ladder\n",
    "\n",
    "A\\* works for every problem that you can describe with states, actions with a cost, and an estimate of the remaining cost. Take this word puzzle: turn one word into another by changing one letter at a time, where every step has to be a real word. From SLEEP to DREAM, for example:\n",
    "\n",
    "SLEEP → SHEEP → CHEEP → CHEEK → CREEK → CREAK → CREAM → DREAM\n",
    "\n",
    "Lewis Carroll, the author of *Alice in Wonderland*, invented this puzzle at Christmas 1877 and called it *Doublets*.\n",
    "\n",
    "As a search problem, a **state** is a word, and the **neighbors** of a word are all real words that differ from it in exactly one letter. Every step costs 1, so the cheapest path is the shortest ladder.\n",
    "\n",
    "First download a list of real words: about 14,800 English words of five letters."
   ]
  },
  {
   "cell_type": "code",
   "id": "2ecc3833",
   "metadata": {},
   "source": [
    "# On your own computer, this installs the package for downloading files (Colab has it already)\n",
    "%pip install --quiet requests\n",
    "import os\n",
    "import requests\n",
    "\n",
    "DATA_URL = \"https://ai.kuleuven.be/aivooriedereen/notebooks/data/\"\n",
    "\n",
    "if os.path.exists(\"data/five-letter-words.txt\"):  # a copy of the word list next to this notebook?\n",
    "    with open(\"data/five-letter-words.txt\") as file:\n",
    "        text = file.read()\n",
    "else:  # otherwise, download it from the website\n",
    "    response = requests.get(DATA_URL + \"five-letter-words.txt\")\n",
    "    response.raise_for_status()  # stop with an error if the download failed\n",
    "    text = response.text\n",
    "words = set(text.split())  # a set: looking up a word in it is instant"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "4454c9a3",
   "metadata": {},
   "source": [
    "print(len(words), \"words\")\n",
    "print(\"Is 'sleep' a word?\", \"sleep\" in words)\n",
    "print(\"Is 'slepp' a word?\", \"slepp\" in words)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e2f60d34",
   "metadata": {},
   "source": [
    "The neighbors of a word: for every position in the word, try all 26 letters, and keep the new words that are in the list."
   ]
  },
  {
   "cell_type": "code",
   "id": "363eef6b",
   "metadata": {},
   "source": [
    "def one_letter_changes(word):\n",
    "    \"\"\"All real words that differ from word in one letter, each with cost 1.\"\"\"\n",
    "    changes = []\n",
    "    for position in range(len(word)):\n",
    "        for letter in \"abcdefghijklmnopqrstuvwxyz\":\n",
    "            # the word with the letter at this position replaced:\n",
    "            new_word = word[:position] + letter + word[position + 1:]\n",
    "            if new_word in words and new_word != word:\n",
    "                changes.append((new_word, 1))\n",
    "    return changes\n",
    "\n",
    "\n",
    "print(one_letter_changes(\"sleep\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5635d353",
   "metadata": {},
   "source": [
    "### 🧭 An estimate that never overestimates\n",
    "\n",
    "A\\* also needs a heuristic: an estimate of how many steps are still needed. Here a simple one works well: count the letters that still differ from the goal word. Every step changes exactly one letter, so you need at least that many steps. From SLEEP to DREAM, four letters differ (only the E in the middle is already right), while the ladder above takes seven steps: the estimate is too low, but never too high. That is exactly what A\\* needs to be sure it finds the shortest ladder."
   ]
  },
  {
   "cell_type": "code",
   "id": "5b873db6",
   "metadata": {},
   "source": [
    "def letters_to_change(word, goal):\n",
    "    \"\"\"How many letters still differ from goal? You need at least that many steps.\"\"\"\n",
    "    different = 0\n",
    "    for position in range(len(word)):\n",
    "        if word[position] != goal[position]:\n",
    "            different = different + 1\n",
    "    return different\n",
    "\n",
    "\n",
    "print(letters_to_change(\"sleep\", \"dream\"))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "142311f5",
   "metadata": {},
   "source": [
    "Now let A\\* search. Type two words of five letters (in lowercase) in the fields next to the code, or change the text between the quotes."
   ]
  },
  {
   "cell_type": "code",
   "id": "cd303a00",
   "metadata": {},
   "source": [
    "start = \"sleep\"  # @param {type:\"string\"}\n",
    "goal = \"dream\"  # @param {type:\"string\"}\n",
    "\n",
    "path, cost = a_star(start, goal, one_letter_changes, letters_to_change)\n",
    "\n",
    "if path is None:\n",
    "    print(\"There is no word ladder from\", start, \"to\", goal)\n",
    "else:\n",
    "    print(\"From\", start, \"to\", goal, \"in\", cost, \"steps:\")\n",
    "    print(path)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e30ca4aa",
   "metadata": {},
   "source": [
    "How much does the estimate help? The cell below lets A\\* count the words it looks at: once with the estimate, and once with an estimate of 0. Without an estimate, A\\* sorts the frontier by the cost so far alone, so it is exactly [uniform cost search](https://ai.kuleuven.be/aivooriedereen/en/heuristic-search#uniform-cost-search) from the chapter."
   ]
  },
  {
   "cell_type": "code",
   "id": "23de65ce",
   "metadata": {},
   "source": [
    "looked_at = []\n",
    "\n",
    "\n",
    "def changes_counted(word):\n",
    "    \"\"\"The same as one_letter_changes, but remembers every word that A* looks at.\"\"\"\n",
    "    looked_at.append(word)\n",
    "    return one_letter_changes(word)\n",
    "\n",
    "\n",
    "def no_estimate(word, goal):\n",
    "    return 0\n",
    "\n",
    "\n",
    "a_star(start, goal, changes_counted, letters_to_change)\n",
    "print(\"With the estimate, A* looked at\", len(looked_at), \"words\")\n",
    "\n",
    "looked_at.clear()\n",
    "a_star(start, goal, changes_counted, no_estimate)\n",
    "print(\"Without an estimate (uniform cost search), A* looked at\", len(looked_at), \"words\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "721b1ee0",
   "metadata": {},
   "source": [
    "Both searches find a ladder of the same length (uniform cost search is just as correct), but with the estimate A\\* looks at far fewer words: for SLEEP to DREAM about 17 times fewer. The bigger the problem, the bigger that difference gets. And did you notice? A\\* found an even shorter ladder than the one at the start of this section.\n",
    "\n",
    "**Try it yourself**\n",
    "\n",
    "- Try other pairs, such as `sword` → `stone`, `brain` → `heart` or `bread` → `toast`.\n",
    "- Can you find a pair where there is no ladder? Hint: some words, such as `pizza`, have no neighbors at all.\n",
    "- Pick two random words: `start = random.choice(sorted(words))`, and the same for `goal` (with `import random` at the top of the cell)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44808a62",
   "metadata": {},
   "source": [
    "## 🗺️ Extra: a real route on OpenStreetMap\n",
    "\n",
    "In practice, the states and actions usually come from data. In this extra part, you download the real road network around two places from [OpenStreetMap](https://www.openstreetmap.org), the free world map that anyone can edit, and let the same `a_star` function plan a route. Just like on the map of Leuven in the chapter, the states are points on the roads and the actions are road segments with a length.\n",
    "\n",
    "You don't need to understand every line below. The point is to see that it doesn't take much code to load real data and run your own A\\* on it.\n",
    "\n",
    "First install [OSMnx](https://osmnx.readthedocs.io), a package that downloads OpenStreetMap data as a graph, together with `folium`, which draws maps. In Colab this takes a few seconds; on your own computer it can take a few minutes."
   ]
  },
  {
   "cell_type": "code",
   "id": "22efcb24",
   "metadata": {},
   "source": [
    "# osmnx downloads the map, folium draws it, scikit-learn finds the nearest road\n",
    "%pip install --quiet osmnx folium scikit-learn"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "30ebc58a",
   "metadata": {},
   "source": [
    "Did the installation stop with a long error that mentions GDAL? Then there is no ready-made build of OSMnx's map libraries for your computer yet (this happens on Windows laptops with an ARM processor, for example). Run this extra part in [Google Colab](https://colab.research.google.com/drive/1l_BnrMiX9Yr-Md-ykKI9byND01HIPRhN?usp=sharing) instead, where the installation works."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d5e0d24",
   "metadata": {},
   "source": [
    "Two helper functions: one to download the roads around two places, and one to draw a route on a map."
   ]
  },
  {
   "cell_type": "code",
   "id": "44fc4432",
   "metadata": {},
   "source": [
    "import folium\n",
    "import osmnx as ox\n",
    "\n",
    "\n",
    "def download_roads(point_a, point_b, network_type=\"drive\", margin=0.01):\n",
    "    \"\"\"Download the roads in a rectangle around two points: for cars (\"drive\"), bikes (\"bike\") or pedestrians (\"walk\").\"\"\"\n",
    "    north = max(point_a[0], point_b[0]) + margin  # 0.01 degrees is about 1 km\n",
    "    south = min(point_a[0], point_b[0]) - margin\n",
    "    east = max(point_a[1], point_b[1]) + margin\n",
    "    west = min(point_a[1], point_b[1]) - margin\n",
    "    rectangle = (west, south, east, north)\n",
    "    return ox.graph_from_bbox(rectangle, network_type=network_type, simplify=False)\n",
    "\n",
    "\n",
    "def show_route(roads, route):\n",
    "    \"\"\"Draw a route (a list of points on the roads) as a red line on a map.\"\"\"\n",
    "    coordinates = []\n",
    "    for node in route:\n",
    "        point = roads.nodes[node]\n",
    "        coordinates.append((point[\"y\"], point[\"x\"]))  # (latitude, longitude)\n",
    "    route_map = folium.Map(tiles=\"Esri.WorldStreetMap\")  # OpenStreetMap's own tile server blocks maps shown in Colab; Esri's free street map doesn't\n",
    "    folium.PolyLine(coordinates, color=\"red\", weight=5).add_to(route_map)\n",
    "    folium.Marker(coordinates[0], tooltip=\"Start\").add_to(route_map)\n",
    "    folium.Marker(coordinates[-1], tooltip=\"Goal\").add_to(route_map)\n",
    "    route_map.fit_bounds(coordinates)  # zoom in on the route\n",
    "    return route_map"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ae311b8a",
   "metadata": {},
   "source": [
    "### 📍 Choose two places\n",
    "\n",
    "Type two places in the fields next to the code (in Colab), or change the text between the quotes, and pick the kind of roads: for cars (`drive`), bikes (`bike`) or pedestrians (`walk`). Then run the cell. For two places 25 km apart, the download takes about 20 seconds: the further apart the places, the larger the map, and the longer it takes.\n",
    "\n",
    "**Changed something here?** Run this cell again, and then the cells below it as well: they search the road network that this cell downloaded."
   ]
  },
  {
   "cell_type": "code",
   "id": "09ab26ba",
   "metadata": {},
   "source": [
    "start_place = \"Universiteitshal, Leuven\"  # @param {type:\"string\"}\n",
    "goal_place = \"Royal Palace, Brussels\"  # @param {type:\"string\"}\n",
    "network_type = \"drive\"  # @param [\"drive\", \"bike\", \"walk\"]\n",
    "\n",
    "# Look up the coordinates (latitude, longitude) of both places\n",
    "start_point = ox.geocode(start_place)\n",
    "goal_point = ox.geocode(goal_place)\n",
    "print(start_place, \"is at\", start_point)\n",
    "print(goal_place, \"is at\", goal_point)\n",
    "\n",
    "# Download the road network around both places\n",
    "roads = download_roads(start_point, goal_point, network_type)\n",
    "print(\"Downloaded\", len(roads.nodes), \"points and\", len(roads.edges), \"road segments\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "49f8e714",
   "metadata": {},
   "source": [
    "If a place can't be found, describe it more precisely, for example with a street address such as \"Naamsestraat 22, Leuven\". If the download fails, the OpenStreetMap server is probably busy: wait a minute and run the cell again.\n",
    "\n",
    "### 🔍 Search with A\\*\n",
    "\n",
    "The road network is a graph: the **nodes** are points on the roads, each with a latitude (`y`) and a longitude (`x`), and the **edges** are the road segments between them, each with a `length` in meters. To search it with `a_star`, you write the same two functions as for the word ladder:\n",
    "\n",
    "- `road_neighbors` gives the points you can drive to directly, with the length of that road segment as the cost;\n",
    "- `straight_line_distance` is the heuristic: the distance as the crow flies. A road is never shorter than a straight line, so this estimate is never too high.\n",
    "\n",
    "Then you look up the point on the roads closest to each place, and search. Did you just change the places or the kind of roads above? Run that cell first, so that `roads` holds the right network."
   ]
  },
  {
   "cell_type": "code",
   "id": "f9c56a74",
   "metadata": {},
   "source": [
    "def road_neighbors(node):\n",
    "    \"\"\"The points you can drive to from node, with the length of each road segment.\"\"\"\n",
    "    neighbors = []\n",
    "    for from_node, to_node, length in roads.edges(node, data=\"length\"):\n",
    "        neighbors.append((to_node, length))\n",
    "    return neighbors\n",
    "\n",
    "\n",
    "def straight_line_distance(node, goal):\n",
    "    \"\"\"The distance as a bird flies between two points, in meters.\"\"\"\n",
    "    a = roads.nodes[node]\n",
    "    b = roads.nodes[goal]\n",
    "    return ox.distance.great_circle(a[\"y\"], a[\"x\"], b[\"y\"], b[\"x\"])\n",
    "\n",
    "\n",
    "start_node = ox.nearest_nodes(roads, X=start_point[1], Y=start_point[0])\n",
    "goal_node = ox.nearest_nodes(roads, X=goal_point[1], Y=goal_point[0])\n",
    "\n",
    "route, length = a_star(start_node, goal_node, road_neighbors, straight_line_distance)\n",
    "print(\"Route found:\", round(length / 1000, 1), \"km\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "d6f66866",
   "metadata": {},
   "source": [
    "show_route(roads, route)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "52aa2428",
   "metadata": {},
   "source": [
    "The red line is the shortest route in distance, not necessarily the fastest one: our A\\* only counts meters, while a navigation app also takes the speed on every road into account. Want to try more?\n",
    "\n",
    "- Choose two places of your own in the cell with the text fields, and run the cells below it again.\n",
    "- How much does the heuristic help here? Search again with `no_estimate` from the word ladder as the heuristic (uniform cost search), and compare how long both searches take, or count the points they look at like you did for the words.\n",
    "- Let A\\* find the fastest route instead of the shortest one: `ox.routing.add_edge_speeds(roads)` followed by `ox.routing.add_edge_travel_times(roads)` gives every road segment a `travel_time` in seconds. Use that as the cost instead of `length`. The heuristic then has to become a time as well: the straight-line distance at the highest speed on the map, so that it still never overestimates.\n",
    "- Plan a bike or walking route between two places in the same city: pick `bike` or `walk` in the dropdown next to the code of 📍 Choose two places (or change the text), and run that cell and the cells below it again. For bikes and pedestrians there are many more paths than for cars, so the download grows quickly with the distance."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3f10413",
   "metadata": {},
   "source": [
    "## 🧰 A\\* for your own problem\n",
    "\n",
    "`a_star` works for every problem that you can describe as a search problem. You only write two functions, just like `one_letter_changes` and `letters_to_change` above:\n",
    "\n",
    "1. **`neighbors(state)`** gives a list of `(next_state, cost)` pairs: all states you can reach with one action, each with the cost of that action. Use simple values as states: a number, a text, or a tuple such as `(row, column)`.\n",
    "2. **`heuristic(state, goal)`** estimates the remaining cost, and may never estimate too high. Can't think of a good estimate? Let it return 0: A\\* then becomes uniform cost search, which is just as correct, but slower.\n",
    "\n",
    "Then `path, cost = a_star(start, goal, neighbors, heuristic)` does the rest. Think of a maze or a board game on a grid (with the Manhattan distance as the estimate), a sliding puzzle, or your daily commute."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48feeff7",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/a-star-search](https://ai.kuleuven.be/aivooriedereen/en/notebook/a-star-search).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "heuristisch-zoeken"
   ],
   "language": "en",
   "title": "A* search in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
