"<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 depth-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, 3, 2, 4, 5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Algorithm\n",
"\n",
"If we want to visit every node in a graph, we generally prefer depth-first search since it is simpler (no need to use a queue). For shortest path, we generally use breadth-first search.\n",
"\n",
"* Visit the current node and mark it visited\n",
"* Iterate through each adjacent node\n",
" * If the node has not been visited, call dfs on it\n",
"\n",
"Complexity:\n",
"* Time: O(V + E), where V = number of vertices and E = number of edges\n",