zoukankan      html  css  js  c++  java
  • [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'])
    

      

      

  • 相关阅读:
    别让你的生活止于平庸!(摘)
    NSURLSession 请求
    第三方原理
    iOS实用的小技巧
    简书APP
    网络请求
    JQuery 简介
    struts2拦截器的实现原理及源码剖析
    hibernate配置文件注意点
    hibernate中三种状态
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9808361.html
Copyright © 2011-2022 走看看