I’m taking a file of symbols:
pipes with openings on specific sides
the source: *
sinks: letters
and using BFS to find which sinks are connected to the source through the pipes, but it is only returning ‘ ‘.
My code starts by opening the file and parsing it into a grid. There is then a function to get the coordinates of neighboring cells. There’s a dictionary to denote which pipes can be connected to each other. Finally, there is a BFS function that starts at the source, *, and finds the sinks that are connected to it. However, the code is only returning ‘ ‘. What could be the issue?
def connected_sinks(file_path):
from collections import defaultdict, deque
def parse_file(file_path):
grid = {}
with open(file_path, 'r') as f:
for line in f:
obj, x, y = line.strip().split()
x, y = int(x), int(y)
grid[(x, y)] = obj
return grid
def get_neighbors(x, y):
return [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]
def is_connected(cell, neighbor, direction):
connections = {
'═': {'left': '═╠╦╩╚╔', 'right': '═╣╦╩╝╗'},
'║': {'up': '║╠╣╦╔╗', 'down': '║╠╣╩╚╝'},
'╔': {'right': '═╣╦╩╝╗', 'down': '║╠╣╩╚╝'},
'╗': {'left': '═╠╦╩╚╔', 'down': '║╠╣╩╚╝'},
'╚': {'right': '═╣╦╩╝╗', 'up': '║╠╣╦╔╗'},
'╝': {'left': '═╠╦╩╚╔', 'up': '║╠╣╦╔╗'},
'╠': {'left': '═╠╦╩╚╔', 'right': '═╣╦╩╝╗', 'down': '║╠╣╩╚╝'},
'╣': {'left': '═╠╦╩╚╔', 'right': '═╣╦╩╝╗', 'down': '║╠╣╩╚╝'},
'╩': {'left': '═╠╦╩╚╔', 'right': '═╣╦╩╝╗', 'up': '║╠╣╦╔╗'},
'╦': {'left': '═╠╦╩╚╔', 'right': '═╣╦╩╝╗', 'down': '║╠╣╩╚╝'}
}
if cell == '*' or neighbor == '*':
return True
if cell in connections and direction in connections[cell]:
return neighbor in connections[cell][direction]
return False
def bfs(grid, start):
queue = deque([start])
visited = set([start])
sinks = set()
while queue:
x, y = queue.popleft()
for (nx, ny), direction in zip(get_neighbors(x, y), ['left', 'right', 'up', 'down']):
if (nx, ny) in grid and (nx, ny) not in visited:
if is_connected(grid[(x, y)], grid[(nx, ny)], direction):
queue.append((nx, ny))
visited.add((nx, ny))
if grid[(nx, ny)].isalpha():
sinks.add(grid[(nx, ny)])
return ''.join(sorted(sinks))
grid = parse_file(file_path)
source = next((pos for pos, val in grid.items() if val == '*'), None)
if source:
return bfs(grid, source)
else:
return ''
None is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.