Skip to content

CSPT13-Karthik-Graphs #752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 87 additions & 16 deletions projects/adventure/adv.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from room import Room
from player import Player
from world import World

from collections import deque
import random
from ast import literal_eval

# Load world
world = World()

#construct a traversal graph
#do dft for finding all the possible room player can move
#do bfs for finding unexplored direction

# You may uncomment the smaller graphs for development and testing purposes.
# map_file = "maps/test_line.txt"
Expand All @@ -24,12 +27,82 @@
world.print_rooms()

player = Player(world.starting_room)
player.current_room = world.starting_room

# Fill this out with directions to walk
# traversal_path = ['n', 'n']
traversal_path = []


backtrack = {
'n': 's',
'e': 'w',
'w': 'e',
's': 'n'}

def bfs(curr_room):
visited = set()
queue = deque()
queue.append((curr_room,[]))

while len(queue)>0:
(room,path) = queue.popleft()
if room in visited:
continue
visited.add(room)
for direction in visited_room[room]:
if visited_room[room][direction] == '?':
return [path,direction]
else:
newPath = path.copy()
newPath.append(direction)
next_room = visited_room[room][direction]
queue.append((next_room,newPath))

def dft(unexplored_diection):
stack = deque()
stack.append(unexplored_diection)

while len(stack)>0:
curr_exit = stack.pop()
move_direction = curr_exit[-1]
if move_direction not in visited_room[player.current_room.id]:
continue
elif visited_room[player.current_room.id][move_direction] == '?':
prev_room = player.current_room.id
player.travel(move_direction)
traversal_path.append(move_direction)

visited_room[prev_room][move_direction] = player.current_room.id
opposite_val = backtrack[move_direction]

if player.current_room.id not in visited_room:
visited_room[player.current_room.id] = {opposite_val:prev_room}
else:
visited_room[player.current_room.id][opposite_val] = prev_room

for direction in player.current_room.get_exits():
if direction not in visited_room[player.current_room.id]:
visited_room[player.current_room.id][direction] = '?'
new_dir = []
new_dir.append(direction)
stack.append(new_dir)

unexplored_diection = bfs(player.current_room.id)

if unexplored_diection != None:
for direction in unexplored_diection[0]:
player.travel(direction)
traversal_path.append(direction)
dft([unexplored_diection[1]])


starting_dir = random.choice(player.current_room.get_exits())

visited_room = {player.current_room.id:{}}
for direction in player.current_room.get_exits():
visited_room[player.current_room.id][direction] = '?'

dft(starting_dir)

# TRAVERSAL TEST
visited_rooms = set()
Expand All @@ -46,17 +119,15 @@
print("TESTS FAILED: INCOMPLETE TRAVERSAL")
print(f"{len(room_graph) - len(visited_rooms)} unvisited rooms")



#######
# UNCOMMENT TO WALK AROUND
#######
player.current_room.print_room_description(player)
while True:
cmds = input("-> ").lower().split(" ")
if cmds[0] in ["n", "s", "e", "w"]:
player.travel(cmds[0], True)
elif cmds[0] == "q":
break
else:
print("I did not understand that command.")
# #######
# # UNCOMMENT TO WALK AROUND
# #######
# player.current_room.print_room_description(player)
# while True:
# cmds = input("-> ").lower().split(" ")
# if cmds[0] in ["n", "s", "e", "w"]:
# player.travel(cmds[0], True)
# elif cmds[0] == "q":
# break
# else:
# print("I did not understand that command.")
59 changes: 57 additions & 2 deletions projects/ancestor/ancestor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,58 @@

def earliest_ancestor(ancestors, starting_node):
pass
from collections import deque, defaultdict

'''
PLAN:
Vertex = People
Edges = parent-child relationships
Weights = not needed
Path = persons family tree

Build Graph:
build graph based on edges given, each user has a directed edge to its ancestor/parent.

Traverse Graph:
traverse all paths starting from start node.
Keep track of farthest node with lowest user ID
output that node.
'''

def earliest_ancestor(ancestors,starting_node):
graph = createGraph(ancestors)

earliest_ancestor = (starting_node,0)

stack = deque()
stack.append((starting_node,0)) # tuple with node ID and its distance from starting node
visited = set()

while len(stack)>0:
curr = stack.pop()
currNode, dist = curr[0],curr[1]
visited.add(curr)

if currNode not in graph: # this means its a terminal node (node with no parent, it won't be the key in graph)
if dist > earliest_ancestor[1]:
earliest_ancestor = curr
elif ((dist == earliest_ancestor[1]) and (currNode < earliest_ancestor[0])):
earliest_ancestor = curr
else:
for ancestor in graph[currNode]:
if ancestor not in visited:
stack.append((ancestor,dist+1))

if earliest_ancestor[0] != starting_node:
return earliest_ancestor[0]
else:
return -1

# vertices = {}
# ancestors = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[8,9],[11,8],[10,1]]

def createGraph(paths): # Building out a graph with child as key and parent as value (directional edge from child to parent.)
graph = defaultdict(set)
for edge in paths:
origin,dest = edge[0],edge[1]
graph[dest].add(origin)
return graph

Loading