Fa20 BCS 083
Fa20 BCS 083
Fa20 BCS 083
Tajamal Hayat
Reg.No:
FA20-BCS-083
Submitted To:
Sir Tahir Rasheed
Question.No.#1
Maze Solver with BFS
Code:
from collections import deque
maze = [
[0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0],
start = (0, 0)
visited = set()
while queue:
if (x, y) == end:
if 0 <= x < len(maze) and 0 <= y < len(maze[0]) and maze[x][y] == 0 and (x, y) not in visited:
visited.add((x, y))
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
return []
if path:
for x, y in path:
else:
Question.No.#2
Directory Tree Search using DFS
Code:
import os
def dfs_directory_tree_search(root_directory):
stack = [root_directory]
while stack:
current_directory = stack.pop()
try:
entries = os.listdir(current_directory)
except Exception as e:
continue
if os.path.isdir(full_path):
print(f"Directory: {full_path}")
stack.append(full_path)
else:
print(f"File: {full_path}")
starting_directory = "/path/to/your/directory"
dfs_directory_tree_search(starting_directory)
else:
Question.No#3
A* Pathfinding Algorithm
Code:
import heapq
class Node:
self.x = x
self.y = y
self.parent = None
# A* pathfinding function
open_list = []
closed_set = set()
heapq.heappush(open_list, start)
while open_list:
current = heapq.heappop(open_list)
if current == end:
path = []
while current:
path.append((current.x, current.y))
current = current.parent
return path[::-1]
closed_set.add(current)
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and grid[new_x][new_y] == 0:
if neighbor in closed_set:
continue
tentative_g = current.g + 1
neighbor.g = tentative_g
neighbor.parent = current
heapq.heappush(open_list, neighbor)
grid = [
[0, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 0]
start = Node(0, 0)
end = Node(4, 4)
if path:
for x, y in path:
else:
Question.No.4
Heuristic values to find the optimal path
Code:
from queue import PriorityQueue
graph = {
'G': {},
'K': {},
'L': {}
frontier = PriorityQueue()
frontier.put((0, start))
came_from = {}
cost_so_far = {start: 0}
_, current = frontier.get()
if current == goal:
break
cost_so_far[neighbor] = new_cost
frontier.put((priority, neighbor))
came_from[neighbor] = current
return path
# Function to reconstruct the path from the start to the goal
current = goal
path = [current]
current = came_from[current]
path.append(current)
path.reverse()
return path
start_node = 'A'
goal_node = 'L'
if path:
else: