0% found this document useful (0 votes)
19 views2 pages

Dfs

The document describes an implementation of depth-first search (DFS) on a graph represented as an adjacency list. It defines a recursive DFS function that takes a graph, starting node, target node, and visited set as parameters. It prints visited nodes, returns true if the target is found, and returns false otherwise. An example graph is provided and DFS is run from node A to search for node F.

Uploaded by

amitesh.ug22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views2 pages

Dfs

The document describes an implementation of depth-first search (DFS) on a graph represented as an adjacency list. It defines a recursive DFS function that takes a graph, starting node, target node, and visited set as parameters. It prints visited nodes, returns true if the target is found, and returns false otherwise. An example graph is provided and DFS is run from node A to search for node F.

Uploaded by

amitesh.ug22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 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