"<small><i>This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).</i></small>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Solution Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Problem: Implement breadth-first search on a graph.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Constraints\n",
"\n",
"* Is the graph directed?\n",
" * Yes\n",
"* Can we assume we already have Graph and Node classes?\n",
" * Yes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test Cases\n",
"\n",
"Input:\n",
"* `add_edge(source, destination, weight)`\n",
"\n",
"```\n",
"graph.add_edge(0, 1, 5)\n",
"graph.add_edge(0, 4, 3)\n",
"graph.add_edge(0, 5, 2)\n",
"graph.add_edge(1, 3, 5)\n",
"graph.add_edge(1, 4, 4)\n",
"graph.add_edge(2, 1, 6)\n",
"graph.add_edge(3, 2, 7)\n",
"graph.add_edge(3, 4, 8)\n",
"```\n",
"\n",
"Result:\n",
"* Order of nodes visited: [0, 1, 4, 5, 3, 2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Algorithm\n",
"\n",
"We generally use breadth-first search to determine the shortest path.\n",
"\n",
"* Add the current node to the queue and mark it as visited\n",
"* While the queue is not empty\n",
" * Dequeue a node and visit it\n",
" * Iterate through each adjacent node\n",
" * If the node has not been visited, add it to the queue and mark it as visited\n",
"\n",
"Complexity:\n",
"* Time: O(V + E), where V = number of vertices and E = number of edges\n",