You are on page 1of 7

AI-LAB NO.

Submitted by: Ayesha Siddiqa Reg# SP22-BSE-009


Submitted to: Sir Waqas Ali Date: 3/11/2024

Activity 1:
def iterative_deepening_dfs(start, target):
depth = 1
bottom_reached = False
while not bottom_reached:
result, bottom_reached = iterative_deepening_dfs_rec(start,
target, 0, depth)
if result is not None:
return result
depth *= 2
print("Increasing depth to " + str(depth))

return None

def iterative_deepening_dfs_rec(node, target, current_depth, max_depth):


print("Visiting node " + str(node["value"]))
if node["value"] == target:
print("Found the node we are looking for!")
print("Goal node " + str(node["value"]))
return node, True

if current_depth == max_depth:
print("Current maximum depth reached, returning..")
if len(node["children"]) > 0:
return None, False
else:
return None, True

bottom_reached = True
for i in range(len(node["children"])):
result, bottom_reached_rec =
iterative_deepening_dfs_rec(node["children"][i], target, current_depth +
1, max_depth)
if result is not None:
return result, True
bottom_reached = bottom_reached and bottom_reached_rec
return None, bottom_reached

start = {
"value": 0,
"children": [
{
"value": 1,
"children": [
{"value": 2, "children": []}
]
},
{
"value": 3,
"children": [
{"value": 4, "children": []},
{"value": 5, "children": []}
]
},
{
"value": 6,
"children": [
{"value": 7, "children": []}
]
},
{
"value": 8,
"children": [
{"value": 9, "children": []}
]
},
{
"value": 10,
"children": [
{"value": 11, "children": []}
]
},
{
"value": 12,
"children": [
{"value": 13, "children": []}
]
},
{
"value": 14,
"children": [
{"value": 15, "children": []}
]
},
{
"value": 16,
"children": []
},
{
"value": 17,
"children": [
{"value": 18, "children": []}
]
},
{
"value": 19,
"children": [
{"value": 20, "children": []},
{"value": 21, "children": []}
]
},
{
"value": 22,
"children": [
{"value": 23, "children": []},
{"value": 24, "children": []}
]
},
{
"value": 25,
"children": [
{"value": 5, "children": []}
]
}
]
}

goalnode = 7
if (iterative_deepening_dfs(start, goalnode) != None):
print(iterative_deepening_dfs(start,goalnode)[0]["value"])
else:
print("Node " , goalnode , "is not found in tree")

Output:
Task 1:
class Graph:
def __init__(self):
self.graphValues = {}

def add_node_and_edges(self, node, edges):


self.graphValues[node] = edges

# Iterative deepening DFS implementation


def iterative_deepening_dfs(self, start, target):
depth = 0
while True:
result, found = self._iddfs_rec(start, target, 0, depth)
if found:
return result
depth += 1
print("Increasing depth to", depth)

def _iddfs_rec(self, node, target, current_depth, max_depth,


visited=None):
if visited is None:
visited = set()

visited.add(node)
if node == target:
return [node], True

if current_depth == max_depth:
return [], False
for neighbor in self.graphValues[node][0]:
if neighbor not in visited:
result, found = self._iddfs_rec(
neighbor, target, current_depth + 1, max_depth,
visited
)
if found:
return [node] + result, True

return [], False

# Path reconstruction
def find_path(self, start, end):
path_nodes = self.iterative_deepening_dfs(start, end)
if path_nodes:
return " -> ".join(path_nodes)
else:
return "No path found."

# Example usage:
graph = Graph()
graph.add_node_and_edges('Oradea', (['Zerind', 'Sibiu'], [71, 151]))
graph.add_node_and_edges('Zerind', (['Oradea', 'Arad'], [71, 75]))
graph.add_node_and_edges('Arad', (['Zerind', 'Sibiu', 'Timisoara'], [75,
140, 118]))
graph.add_node_and_edges('Timisoara', (['Arad', 'Lugoj'], [118, 111]))
graph.add_node_and_edges('Lugoj', (['Mehadia', 'Timisoara'], [70, 111]))
graph.add_node_and_edges('Mehadia', (['Lugoj', 'Drobeta'], [70, 75]))
graph.add_node_and_edges('Drobeta', (['Mehadia', 'Craiova'], [75, 120]))
graph.add_node_and_edges('Sibiu', (['Oradea', 'Rimnicu Vilcea', 'Arad',
'Fagaras'], [151, 80, 140, 99]))
graph.add_node_and_edges('Rimnicu Vilcea', (['Sibiu', 'Craiova',
'Pitesti'], [80, 146, 97]))
graph.add_node_and_edges('Craiova', (['Drobeta', 'Rimnicu Vilcea',
'Pitesti'], [120, 146, 138]))
graph.add_node_and_edges('Fagaras', (['Sibiu', 'Bucharest'], [99, 211]))
graph.add_node_and_edges('Pitesti', (['Rimnicu Vilcea', 'Craiova',
'Bucharest'], [97, 138, 101]))
graph.add_node_and_edges('Bucharest', (['Pitesti', 'Fagaras', 'Giurgiu',
'Urziceni'], [101, 211, 90, 85]))
graph.add_node_and_edges('Giurgiu', (['Bucharest'], [90]))
graph.add_node_and_edges('Urziceni', (['Bucharest', 'Hirsova', 'Vaslui'],
[85, 98, 142]))
graph.add_node_and_edges('Hirsova', (['Urziceni', 'Eforie'], [98, 86]))
graph.add_node_and_edges('Eforie', (['Hirsova'], [86]))
graph.add_node_and_edges('Vaslui', (['Urziceni', 'Iasi'], [142, 92]))
graph.add_node_and_edges('Iasi', (['Vaslui', 'Neamt'], [92, 87]))
graph.add_node_and_edges('Neamt', (['Iasi'], [87]))
# Find path between nodes
start_node = 'Arad'
end_node = 'Bucharest'
path = graph.find_path(start_node, end_node)
print("Path:", path)

Output:

Task 2:
def find_words(board, dictionary):
"""
Finds all possible words that can be formed on a Boggle board.

Args:
board: A 2D list representing the Boggle board.
dictionary: A set of valid words to check against.

Returns:
A set of all the valid words found on the Boggle board.
"""

rows, cols = len(board), len(board[0])


visited = set() # Keeps track of visited cells to avoid revisiting
words = set()

def dfs(row, col, word):


"""
Recursive DFS helper function to explore the Boggle board.

Args:
row: The current row index.
col: The current column index.
word: The current word being built.
"""

if word in dictionary:
words.add(word)

# Mark the current cell as visited and append it to the word


visited.add((row, col))
word += board[row][col]
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1),
(1, -1), (1, 1)]:
# Explore all eight directions around the current cell
new_row, new_col = row + dr, col + dc

# Check if the new cell is within board boundaries and not visited
if 0 <= new_row < rows and 0 <= new_col < cols and (new_row,
new_col) not in visited:
dfs(new_row, new_col, word)

# Backtrack: remove the current cell from visited and the word
visited.remove((row, col))
word = word[:-1]

# Start DFS at each cell of the board


for row in range(rows):
for col in range(cols):
dfs(row, col, "")

return words

# Example usage
board = [
['M', 'S', 'E', 'F'],
['R', 'A', 'T', 'D'],
['L', 'O', 'N', 'E'],
['K', 'A', 'F', 'B']
]

dictionary = set(["START", "NOTE", "SAND", "STONED"])

words = find_words(board, dictionary)


print("Valid words found:", words)

Output:

You might also like