HOGWARTS SCHOOL
Submitting Case Study in Artificial
Intelligence CSEN2031
By
SURYA BABITHA ADARI
VU22CSEN0400099
Under the Guidance of
Murthy V.S.V.S
Dr Sankara Rao Parasana
FEBRUARY2025
1. Introduction
Overview of CaseStudy
1. BFS: Exploring Hogwarts Castle
Goal: Find the shortest routes between key locations while navigating
moving staircases, magical creatures, and hidden doors.
Challenges: Dynamic paths, restricted areas, and time-sensitive shortcuts.
Extensions: Introducing magical keys and time-based pathways for deeper
complexity.
2. Bidirectional Search: Triwizard Maze
Goal: Locate the Goblet of Fire using two simultaneous search points,
optimizing for the shortest path.
Challenges: Synchronizing movements, avoiding dynamic obstacles, and
handling decoy goblets.
Extensions: Enchanted objects for partial maze visibility and cooperative
puzzle-solving.
3. Simulated Annealing: Wand Customization
Goal: Optimize wand properties (wood, core, length) for maximum
performance.
Challenges: Balancing rare material benefits, handling misfires, and ensuring
stable optimization.
Extensions: Material trading and compatibility tests for customized
spellcasting.
Objectives of the CaseStudy
Magical
Objective Algorithm Real-World Parallel
Equivalent
Exploring
Find shortest routes in a dynamic Pathfinding in smart
1 BFS Hogwarts Castle
environment cities
Optimize navigation with two entry Bidirectional Triwizard Maze GPS route
2
points Search Challenge optimization
Hyperparameter
Customize wand attributes for best Simulated Wand
3 tuning in machine
performance Annealing Customization
learning
2. Tasks and Solutions
2.11. Breadth-First Search (BFS): Exploring the Castle
Explanation of the Task
A new student arrives at Hogwarts and must navigate the sprawling
castle to locate specific classrooms and facilities, such as the Potions
classroom and the Room of Requirement. The moving staircases,
enchanted walls, and restricted areas create a dynamic and challenging
environment.
PEAS Description
PEAS Element Code Representation
Performance (Minimize
BFS ensures shortest path exploration
traversal time)
Environment (Dynamic Moving staircases and hidden passages are
obstacles) simulated
Actuators (Student
Queue-based traversal for location discovery
movement)
Sensors (Castle layout
Explored nodes track visited locations
awareness)
Task Environment Properties
Partially Observable: Hidden doors and shifting corridors
Stochastic: Moving staircases and magical creatures
Sequential: Choosing a path influences future options
Problem Formulation
Element Description
States Current location (e.g., "Dungeons")
Actions Move to adjacent locations
Goal Reach target (e.g., "Room of Requirement")
Cost Number of steps (shortest path)
Explanation of Algorithm Utilized
BFS ensures the shortest path in Hogwarts Castle by:
Exploring all possible routes level by level
Using a queue to maintain the order of exploration
Keeping track of visited locations to prevent cycles
Explanation of how the algorithm is utilized to perform the task
Phase 1: Summoning the Marauder's Map
Code:
def show_marauders_map():
img = [Link]('The Marauders [Link]') # Load map image
[Link](img)
[Link]('off')
📜
[Link](" The Marauder's Map ") 📜
[Link](block=False)
[Link](3)
Action:
Displays the Marauder’s Map
Gives players a brief pause to observe the castle layout
Hogwarts Analogy:
"Before starting the journey, the Marauder’s Map reveals the
magical pathways within Hogwarts!"
Phase 2: BFS Pathfinding in Hogwarts
Code:
def bfs_hogwarts_castle(graph, start, goal):
queue = deque([(start, [start])]) # BFS queue initialization
visited = set() # Track visited locations
while queue:
current, path = [Link]() # Dequeue next location
if current == goal:
🔮
print(" The path has been revealed! Follow this route safely:")
return path # Found shortest path
if current in visited:
continue
[Link](current)
for neighbor in [Link](current, []): # Explore adjacent locations
if neighbor not in visited:
[Link]((neighbor, path + [neighbor]))
print("⚠️ No magical path found!")
return None
Action:
Queue-Based Exploration: Expands outward from the start location
Shortest Path Guarantee: BFS always finds the shortest route
Avoids Infinite Loops: The visited set prevents revisiting locations
Hogwarts Analogy:
"Filch is chasing you! BFS ensures you reach the Room of Requirement through the shortest
magical route before getting caught!"
Phase 3: User Interaction - Exploring the Castle
Code:-
📍
start_location = input(" Where are you currently? ").strip().title()
📍
destination = input(" Where do you want to go? ").strip().title()
path = bfs_hogwarts_castle(hogwarts_graph, start_location, destination)
if path:
🛤️
print(" Shortest Path:", " -> ".join(path))
else:
print("No path found between the locations.")
Action:
Takes user input for start and destination
Calls BFS to determine the shortest path
Outputs a step-by-step route
Hogwarts Analogy:
"Lost in Hogwarts? Let me guide you! Just tell me where you are and where you want to go,
and I’ll find the safest path!
Code screenshors
output:
2.2 6. Bidirectional Search: Triwizard Maze
Explanation of the Task
As part of the Triwizard Tournament, a student navigates a maze
starting from two different entry points to retrieve the Goblet of Fire.
PEAS Description
Component Description
Performance (Minimize traversal
Bidirectional search reduces search depth
time)
Environment (Dynamic obstacles) Shifting walls and decoy Goblets are considered
Actuators (Maze traversal) Simultaneous search from two points
Sensors (Maze awareness) Explored states track known paths
Task Environment Properties
Partially Observable: Some paths may be hidden initially
Stochastic: Randomly appearing obstacles affect traversal
Sequential: Moving through a section changes available path
Problem Formulation
Element Description
States "Current position in the maze (e.g., (x, y) coordinates)"
"Move to adjacent valid positions (up, down, left,
Actions
right) if not blocked"
Goal Test "state == Goblet's position (goal coordinates)"
"Total number of steps taken (minimizing distance
Path Cost
traversed)"
"Estimated shortest path to the goal from both start
Heuristic
and goal sides
Explanation of Algorithm Utilized
✅ Optimality → Ensures shortest path by meeting in the middle from
both directions.
✅ Memory Efficiency → Stores only partial paths from both
directions instead of exploring the entire maze.
✅ Adaptability → Handles dynamic obstacles and adjusts
pathfinding accordingly.
Key Features of Bidirectional Search
🔹 Expands nodes from both the start and goal simultaneously.
🔹 Stops when both searches meet, ensuring shortest possible route.
🔹 Uses two search fronts, making it faster than standard BFS.
🔹 Reduces redundant exploration by leveraging information from
both sides.
This approach is highly efficient for large mazes compared to a single-
direction search!🚀
Explanation of how the algorithm is utilized to perform the task
Step 11. Import Libraries
import [Link] as plt
import numpy as np
from collections import deque
2. Maze Visualization
def draw_maze(maze, path=None):
[Link](figsize=(8, 8))
[Link](maze, cmap="gray_r")
if path:
for x, y in path:
maze[x, y] = 0.5 # Highlight path in light gray
[Link]([])
[Link]([])
[Link]()
3. Bidirectional Search Function
def bidirectional_search(maze, start, goal):
rows, cols = [Link]
queue_start = deque([(start, [start])])
queue_goal = deque([(goal, [goal])])
visited_start = {start: [start]}
visited_goal = {goal: [goal]}
4. Expanding the Search
def expand(queue, visited_this, visited_other, maze):
current, path = [Link]()
x, y = current
Dequeues the first node and extracts the current position
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx, ny = x + dx, y + dy
5. Generating a Custom Maze
def generate_maze(rows, cols, num_obstacles):
maze = [Link]((rows, cols))
print("\nEnter obstacle positions as x y (0-based index), type 'done'
Only one step available: 'Final stir'.
when finished:")
for _ in range(num_obstacles):
x, y = map(int, input("Obstacle at: ").split())
maze[x, y] = 0 # Mark obstacles
return maze
6. Taking User Inputs
rows = int(input("Enter maze rows: "))
cols = int(input("Enter maze columns: "))
num_obstacles = int(input("Enter number of obstacles: "))
maze = generate_maze(rows, cols, num_obstacles)
start = tuple(map(int, input("Enter start position (x y): ").split()))
goal = tuple(map(int, input("Enter goal position (x y): ").split()))
7. Running the Search & Displaying Results
path = bidirectional_search(maze, start, goal)
draw_maze(maze, path)
if path:
🏆 Path to the Goblet of Fire found!")
print("
else:
❌ No path found!")
print("
Code :-
Output:-
2.3. Simulated Annealing: Wand Customization
Explanation of the Task
A student customizes their wand for maximum compatibility and performance
using rare materials.
PEAS Description
Component Description
Performance (Optimize wand
attributes) Simulated annealing refines wood, core, and
length
Environment (Material limitations) Stability and rarity affect effectiveness
Actuators (Customization choices) Iterative improvement through annealing
Sensors (Wand testing feedback) Spell success rate determines effectiveness
Task Environment Properties
Partially Observable: Some material properties are uncertain
initially
Stochastic: Random failures or misfires occur during testing
Sequential: Cooling schedule affects optimization process
Steps of the Simulated Annealing Wand Customization
Algorithm
User Preferences Input → The user selects their preferred core,
wood, and wand length.
Initialize Parameters → Set initial temperature, cooling rate, and
max iterations.
Evaluate Initial Wand → Compute its fitness based on spell
compatibility and stability.
Simulated Annealing Loop:
🔹 Generate a small variation (neighbor wand).
🔹 Calculate new fitness.
🔹 Accept the new wand if better OR probabilistically if worse.
🔹 Reduce temperature gradually.
Repeat Until Convergence → Stops when the temperature is too low
or no better solutions are found.
Trade Materials (Optional) → User can swap core, wood, or length
for further refinement.
Final Wand Display → Show the optimized wand with best attributes
and fitness score.
Result → The user gets a wand customized for optimal spell
performance!
Code:-
Output:-
3. Conclusion:-
Through the application of AI-driven search techniques, we have
explored three unique problem scenarios within the magical world of
Hogwarts, each leveraging a distinct algorithm for optimal decision-
making:
Breadth-First Search (BFS) for Exploring the Castle
Ensures systematic and complete exploration, finding the shortest
paths while navigating dynamic staircases, hidden doors, and magical
creatures.
Bidirectional Search for the Triwizard Maze
Enhances efficiency by searching from both the start and goal, reducing
unnecessary exploration and quickly identifying the shortest path to the
Goblet of Fire while adapting to shifting walls and decoy traps.
Simulated Annealing for Wand Customization
Optimizes wand attributes for maximum spell compatibility and
stability, balancing trade-offs between rare materials and performance
through intelligent exploration.
Each approach showcases the power of AI in solving complex, dynamic
problems by leveraging structured exploration (BFS), dual-front search
efficiency (Bidirectional Search), and adaptive optimization (Simulated
Annealing). These techniques not only enhance problem-solving in
magical settings but also demonstrate their real-world applicability in
robotics, navigation, and optimization challenges.