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'])
    

      

      

  • 相关阅读:
    JS 原型模式 工厂模式 构造函数的区别
    JS 深入1
    理解DOM的一个例子
    Fuzzing参数
    神经网络相关知识和概念整理
    [转载] 系统、模型和仿真
    frp内网穿透,从外网访问内网资源
    常用软件配置
    141. 环形链表
    501. 二叉搜索树中的众数
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9808361.html
Copyright © 2011-2022 走看看