AI codes(1)
AI codes(1)
class Graph:
def __init__(self):
self.graph = {}
visited.add(start)
print(start, end=" ")
if start == goal:
print("\nGoal found!")
return True
visited.add(start)
print(start, end=" ")
if start == goal:
print("\nGoal found!")
return True
if depth_limit <= 0:
return False # Stop when depth limit is reached
# Example Usage:
g = Graph()
g.add_edge('A', 'B')
g.add_edge('A', 'C')
g.add_edge('B', 'D')
g.add_edge('B', 'E')
g.add_edge('C', 'F')
g.add_edge('C', 'G')
print("DFS Traversal:")
g.dfs('A', 'G')
class Graph:
def __init__(self):
self.graph = {} # Adjacency list
while queue:
node, path = queue.popleft()
if node in visited:
continue
visited.add(node)
if node == goal:
print(f"BFS Path Found: {' → '.join(path)}")
return path # Return the first found path
while priority_queue:
cost, node, path = heapq.heappop(priority_queue)
if node == goal:
print(f"UCS Path Found: {' → '.join(path)} with Cost: {cost}")
return path, cost # Return path and cost
# Example Usage:
g = Graph()
g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 4)
g.add_edge('B', 'D', 2)
g.add_edge('B', 'E', 5)
g.add_edge('C', 'F', 3)
g.add_edge('C', 'G', 7)
g.add_edge('D', 'H', 6)
g.add_edge('E', 'H', 4)
g.add_edge('F', 'H', 2)
print("\nBFS Search:")
g.bfs('A', 'H')
print("\nUCS Search:")
g.ucs('A', 'H')
EXP 4
import heapq
class Graph:
def __init__(self):
self.graph = {} # Adjacency list
self.heuristics = {} # Stores heuristic values for A* and GBFS
while priority_queue:
_, node, path = heapq.heappop(priority_queue)
if node in visited:
continue
visited.add(node)
if node == goal:
print(f"GBFS Path Found: {' → '.join(path)}")
return path # Return the first found path
while priority_queue:
f, g, node, path = heapq.heappop(priority_queue)
# Example Usage:
g = Graph()
g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 4)
g.add_edge('B', 'D', 2)
g.add_edge('B', 'E', 5)
g.add_edge('C', 'F', 3)
g.add_edge('C', 'G', 7)
g.add_edge('D', 'H', 6)
g.add_edge('E', 'H', 4)
g.add_edge('F', 'H', 2)
print("\nA* Search:")
g.a_star_search('A', 'H')
EXP 5
import random
import numpy as np
# New population
population = selected + offspring
for _ in range(max_iterations):
# Generate a random neighbor
neighbor = current_x + random.choice([-step_size, step_size])
# Evaluate fitness
neighbor_fitness = fitness_function(neighbor)