Dfs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

{

"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"source": [
"def dfs(graph, start, target, visited=None):\n",
" if visited is None:\n",
" visited = set()\n",
" visited.add(start)\n",
" print(start, end=' ') # Print the visited node\n",
" if start == target:\n",
" print(\"\\nTarget node found!\")\n",
" return True\n",
"\n",
" for neighbor in graph[start]:\n",
" if neighbor not in visited:\n",
" if dfs(graph, neighbor, target, visited):\n",
" return True\n",
"\n",
" return False\n",
"\n",
"# Example graph represented as an adjacency list\n",
"graph = {\n",
" 'A': ['B', 'C'],\n",
" 'B': ['A', 'D', 'E'],\n",
" 'C': ['A', 'F'],\n",
" 'D': ['B'],\n",
" 'E': ['B', 'F'],\n",
" 'F': ['C', 'E']\n",
"}\n",
"\n",
"# Starting node for DFS\n",
"start_node = 'A'\n",
"# Target node to search for\n",
"target_node = 'F'\n",
"\n",
"\n",
"if not dfs(graph, start_node, target_node):\n",
" print(\"\\nTarget node not found!\")\n"
],
"metadata": {
"id": "6QOLbwfP5kh-",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "44d31a04-e275-4c34-e8c9-84e83a109fde"
},
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"A B D E F \n",
"Target node found!\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# New Section"
],
"metadata": {
"id": "GcqCITmvpR7T"
}
}
]
}

You might also like