Skip to content

Instantly share code, notes, and snippets.

@ibrahimsha23
Created August 11, 2021 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibrahimsha23/33df09f6d64a908bdc8f3f73512ad6e0 to your computer and use it in GitHub Desktop.
Save ibrahimsha23/33df09f6d64a908bdc8f3f73512ad6e0 to your computer and use it in GitHub Desktop.
from collections import deque
class Solution(object):
grid = None
boundary = None
food_path_distance = None
queue_counter = deque()
visited = {}
def getFood(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
print(grid)
self.grid = grid
pin_point = ()
self.boundary = (len(grid)-1, len(grid[0])-1)
for row_index, row_ele in enumerate(grid):
for col_index, col_ele in enumerate(row_ele):
if col_ele == "*":
pin_point = (row_index, col_index, 0)
self.visited = {pin_point: 1}
self.queue_counter.append(pin_point)
self.bfs()
return -1 if not self.food_path_distance else self.food_path_distance
def bfs(self):
counter = 0
while len(self.queue_counter) > 0:
pop_ele = self.queue_counter.popleft()
self.visited[(pop_ele[0], pop_ele[1])] = 1
current_ele = self.validate_xobj_ele(pop_ele)
adj_ele = self.traverse_grid(pop_ele)
if current_ele in ["O", "*"]:
for row, column, counter in adj_ele:
if not row == None and not self.visited.get((row, column), None) and not self.grid[row][column] == "X":
self.queue_counter.append((row, column, counter))
elif current_ele == "#":
self.food_path_distance = self.food_path_distance if self.food_path_distance and self.food_path_distance <= pop_ele[2] else pop_ele[2]
return
def traverse_grid(self, xobj):
counter = xobj[2] + 1
xobj_ele = [
(xobj[0] - 1, xobj[1], counter) if xobj[0] > 0 else (None, None, counter),
(xobj[0] + 1, xobj[1], counter) if not xobj[0] >= self.boundary[0] else (None, None, counter),
(xobj[0], xobj[1] - 1, counter) if xobj[1] > 0 else (None, None, counter),
(xobj[0], xobj[1] + 1, counter) if not xobj[1] >= self.boundary[1] else (None, None, counter),
]
# print(xobj_ele)
return xobj_ele
def validate_xobj_ele(self, xobj_ele):
row, column, counter = xobj_ele
if not row == None:
current_ele = self.grid[row][column]
return current_ele
# print(row, column)
data = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
sol = Solution()
print(sol.getFood(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment