शुरू करेंमुफ़्त में शुरू करें

BFS से किसी ग्राफ़ वर्टेक्स को खोजना

इस अभ्यास में, आप BFS एल्गोरिदम को मॉडिफाई करके ग्राफ़ के भीतर दिए गए वर्टेक्स को खोजेंगे.

आपके कोड को टेस्ट करने में मदद के लिए, निम्न ग्राफ़ को एक dictionary का उपयोग करके लोड किया गया है.

Graphical representation of a graph.

graph = {
  '4' : ['6','7'],
  '6' : ['4', '7', '8'],
  '7' : ['4', '6', '9'],
  '8' : ['6', '9'],
  '9' : ['7', '8']
}

यह अभ्यास पाठ्यक्रम का हिस्सा है

Python में Data Structures और Algorithms

पाठ्यक्रम देखें

अभ्यास निर्देश

  • जाँचें कि क्या आपने search value ढूँढ ली है.
  • अगर search value मिल जाए तो True रिटर्न करें.
  • for लूप के अंदर जाँचें कि adjacent vertex विज़िट किया गया है या नहीं.
  • अगर search value नहीं मिले तो False रिटर्न करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

import queue

def bfs(graph, initial_vertex, search_value):
  visited_vertices = []
  bfs_queue = queue.SimpleQueue()
  visited_vertices.append(initial_vertex)
  bfs_queue.put(initial_vertex)

  while not bfs_queue.empty():
    current_vertex = bfs_queue.get()
    # Check if you found the search value
    if ____:
      # Return True if you find the search value
      ____    
    for adjacent_vertex in graph[current_vertex]:
      # Check if the adjacent vertex has been visited
      if adjacent_vertex not in ____:
        visited_vertices.append(adjacent_vertex)
        bfs_queue.put(adjacent_vertex)
  # Return False if you didn't find the search value
  ____

print(bfs(graph, '4', '8'))
कोड संपादित करें और चलाएँ