0% found this document useful (0 votes)
35 views6 pages

Anmolap2 1

The document discusses two tasks related to graphs. Task 1 involves finding shortest distances between nodes in a graph using breadth-first search. Task 2 involves calculating the probability of escaping a maze represented as a graph. Source code is provided to solve both tasks.

Uploaded by

kartik soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views6 pages

Anmolap2 1

The document discusses two tasks related to graphs. Task 1 involves finding shortest distances between nodes in a graph using breadth-first search. Task 2 involves calculating the probability of escaping a maze represented as a graph. Source code is provided to solve both tasks.

Uploaded by

kartik soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment-5
Student Name: Anmol kumar srivastava UID: 21BCS2984
Branch: CSE Section/Group: 627-A
Semester: 5th Date of Performance: 11/09/2023
Subject Name: Advanced programming lab Subject Code: 21CSP-259

1. Aim:
TASK-1: Consider an undirected graph where each edge weighs 6 units.
Each of the nodes is labelled consecutively from 1 to n. You will be given
a number of queries. For each query, you will be given a list of edges
describing an undirected graph. After you create a representation of the
graph, you must determine and report the shortest distance to each of the
other nodes from a given starting position using the breadth-first search
algorithm (BFS). Return an array of distances from the start node in node
number order. If a node is unreachable, return -1 for that node.

TASK-2: Alef the Frog is in an m x n two-dimensional maze represented


as a table. The maze has the following characteristics:
• Each cell can be free or can contain an obstacle, an exit, or a mine.
• Any two cells in the table considered adjacent if they share a side.
• The maze is surrounded by a solid wall made of obstacles. Some
pairs of free cells are connected by a bidirectional tunnel.

2. Objective: To understand the concept of graphs.

3. Source Code:
TASK-1:
import math
import os
import random
import re
import sys
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

class Node:
def __init__(self, val):
self.val = val
self.visited = False
self.neighbors = []
def __repr__(self):
return str(self.val)

def __str__(self):
return str({"node":self.val, "neighbors":self.neighbors, "visted":self.visited})
def add_neighbor(self, neighbor):
if neighbor.val != self.val and neighbor.val not in self.neighbors :
self.neighbors.append(neighbor.val)

def bfs(n, m, edges, s):


graph = {}
# init the graph with nodes with no edges
for i in range(n):
node = i +1
graph[node] = Node(node)
# add edges to the graph
for edge in edges:
n1,n2 = edge
n1, n2 = graph[n1], graph[n2]
n1.add_neighbor(n2)
n2.add_neighbor(n1)
cost = 6
queue = [s] # start off with the start node
distances = [-1] * n # init all distances with -1
distances[s-1] = 0 # the start node has a distance of zero
while queue:
node = queue.pop(0)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

node = graph[node]
if node.visited:
continue # move on to the next item in the queue
node.visited=True
for neighbor in node.neighbors:
queue.append(neighbor)
neighbor = graph[neighbor]

current_node_idx = node.val - 1
neighbor_node_idx= neighbor.val -1
if distances[neighbor_node_idx] == -1:
distances[neighbor_node_idx] = distances[current_node_idx] + cost

distances.pop(s-1) # pop the index of the start node


# print(distances)
return distances

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
for q_itr in range(q):
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
edges = []
for _ in range(m):
edges.append(list(map(int, input().rstrip().split())))
s = int(input().strip())
result = bfs(n, m, edges, s)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

TASK-2:

from fractions import Fraction as F

n, m, k = map(int, input().split())
N=n*m
z = [input().strip() for _ in range(n)]
t = list(range(N + 1))
for _ in range(k):
a, b, c, d = map(int, input().split())
a = (a - 1) * m + b - 1
b = (c - 1) * m + d - 1
t[a] = b
t[b] = a

k=0
g = [[set(), set(), F(0)] for _ in range(N + 1)]
d = set(range(N))
start = None

for i in range(n):
for j in range(m):
if z[i][j] == 'A':
d.remove(k)
start = k
if z[i][j] == '%':
g[k][1].add(N)
elif z[i][j] in 'OA':
if i > 0 and z[i - 1][j] != '#':
g[k][1].add(t[k - m])
if i + 1 < n and z[i + 1][j] != '#':
g[k][1].add(t[k + m])
if j > 0 and z[i][j - 1] != '#':
g[k][1].add(t[k - 1])
if j + 1 < m and z[i][j + 1] != '#':
g[k][1].add(t[k + 1])
k += 1

for i, j in enumerate(g):
if j[1]:
for k in j[1]:
g[k][0].add(i)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

k = F(1, len(j[1]))
j[1] = {l: k for l in j[1]}

while d:
v = d.pop()
gv = g[v]
if all(gv[:2]):
loop = 1 / (1 - gv[2])
for u in gv[0]:
gu = g[u]
uv = gu[1].pop(v)
for w, c in gv[1].items():
if w == u:
gu[2] += uv * loop * c
else:
gu[1][w] = uv * loop * c + gu[1].get(w, 0)
g[w][0].add(u)
g[w][0].discard(v)

a, b, c = g[start]
if N in b:
print(float(b[N] / (1 - c)))
else:
print(0)

4. Output:
TASK-1:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

TASK-2:

5. Learning Outcomes:
1. Understood the concept of graphs.
2. Understood the concept of how to traverse in graph.

You might also like