[Google] Help employee find the nearest gbike

You are given a campus map with the Google buildings, roads and Google 
bikes. You have to help the employee find the nearest Google bike. 

Campus map:

. - Free path/road
# - Building
B - Google bike

Employee location - (x, y) - (1, 2)

. . . . . #
. . E . . #
# # # # . #
. B . . . .
. . . . . B

https://www.careercup.com/question?id=5687196447670272

解法:BFS

Python:

from collections import deque

# This function returns the minimum cost
def bfs(googleMap, employeeLocation):
  if not googleMap or not googleMap[0] or not employeeLocation:
    return 0

  minCost = 0
  pathToBuilding = []
  rows, cols = len(googleMap), len(googleMap[0])
  # Perform a BFS here
  startX, startY = employeeLocation
  queue = deque([(startX, startY, 0, [])])
  visited = set([(employeeLocation)])

  while queue:
    x, y, currCost, path = queue.popleft()

    if googleMap[x][y] == 'B': # Destination Reached
      minCost = currCost
      pathToBuilding = path
      break

    for nextX, nextY, dir in [(x, y+1, 'R'), (x+1, y, 'D'), (x, y-1,'L'), (x-1, y, 'U')]:
      if 0 <= nextX < rows and 0 <= nextY < cols \
          and googleMap[nextX][nextY] != '#'\
          and (nextX, nextY) not in visited:

        visited.add((nextX, nextY))
        queue.append((nextX, nextY, currCost + 1, path + [dir]))

  return (minCost, pathToBuilding)

TestCase:

# Test Case 1
googleMap = [
  ['.', '.', '.', '.', '.', '#'],
  ['.', '.', 'E', '.', '.', '#'],
  ['#', '#', '#', '#', '.', '#'],
  ['.', 'B', '.', '.', '.', '.'],
  ['.', '.', '.', '.', '.', 'B']
]
print(bfs(googleMap, (1, 2)))
# OUTPUTS: (6, ['R', 'R', 'D', 'D', 'R', 'D'])

# Test Case 2
googleMap = [
  ['.', '.', '.', '.', '.', '#'],
  ['.', '.', 'E', '.', '.', '#'],
  ['#', '#', '#', '#', '.', '#'],
  ['B', '.', '.', '.', '.', '.'],
  ['.', '.', '.', '.', '.', '.']
]
print(bfs(googleMap, (1, 2)))
# OUTPUTS: (8, ['R', 'R', 'D', 'D', 'L', 'L', 'L', 'L'])

  

  

 

posted @ 2018-10-18 08:08  轻风舞动  阅读(808)  评论(0编辑  收藏  举报