网格路径计数器

问题描述 投票:0回答:1

编写一个迭代函数 num_of_steps,它接受 4 个参数,即 x 和 y co 终点的坐标,x 和 y,迷宫的宽度,W 和迷宫的高度,H。 函数返回从左下角(原点)开始导航的步数 使用嵌套循环将迷宫移动到指定的终点。

python iteration
1个回答
0
投票
def num_of_steps(x, y, W, H, maze):
  """
  This function calculates the number of steps to navigate from the bottom-left corner
  of the maze to the specified ending point, taking walls into account

  Args:
    x: The x coordinate of the ending point.
    y: The y coordinate of the ending point.
    W: The width of the maze.
    H: The height of the maze.
    maze: A 2D list representing the maze layout.
          Values in the maze can represent different things (e.g., 0 for an open 
          path, 1 for a wall)

  Returns:
    The number of steps to navigate from the bottom-left corner to the ending point,
    or None if no path exists.
  """

  steps = 0
  current_x = 0
  current_y = 0

  while current_x != x or current_y != y:
    # Move right  
    while current_x < x and current_x + 1 < W and maze[current_y][current_x + 1] != 1: 
      current_x += 1
      steps += 1

    # Move up 
    while current_y < y and current_y + 1 < H and maze[current_y + 1][current_x] != 1: 
      current_y += 1
      steps += 1

    # Move left 
    while current_x > x and current_x - 1 >= 0 and maze[current_y][current_x - 1] != 1:
      current_x -= 1
      steps += 1

    # Move down 
    while current_y > y and current_y - 1 >= 0 and maze[current_y - 1][current_x] != 1:
      current_y -= 1
      steps += 1

    # Check if we're stuck (can't move in any valid direction)
    if not any([
        current_x < x and current_x + 1 < W and maze[current_y][current_x + 1] != 1,
        current_y < y and current_y + 1 < H and maze[current_y + 1][current_x] != 1,
        current_x > x and current_x - 1 >= 0 and maze[current_y][current_x - 1] != 1,
        current_y > y and current_y - 1 >= 0 and maze[current_y - 1][current_x] != 1
    ]):
      return None  # No path exists

  return steps
© www.soinside.com 2019 - 2024. All rights reserved.