寻找一种更有效的方法来描述一个网格状矩形,使机器人能够触摸矩形内的每个点

我一直在尝试编写一个解决方案,让机器人触摸正方形网格或矩形网格上的每个点。

到目前为止,我一直在研究一个螺旋解决方案,从左下角开始,螺旋向中心移动,我已经让它运行起来了,并且它似乎适用于偶数(正方形)或奇数(矩形)网格。

我想知道是否有一种更有效或更优雅的解决方案,在代码方面比我下面的解决方案更好?

我对编码还比较新,我希望能得到一些反馈,了解如何改进这个代码,或者是否有一个更简单的数学解决方案等等。

例如:一个 5 x 5 网格,[S] 是起始位置,向着位置 25 螺旋前进

[05][06][07][08][09]
[04][19][20][21][10]
[03][18][25][22][11]
[02][17][24][23][12]
[01][16][15][14][13]
[st]

目前我的代码看起来是这样的,可以正常工作。它不需要是螺旋的,只是代码目前的工作方式。

function MoveSides(depth, width)
    local moving = true
    -- 第一组指令设置为变量,并在触摸外部网格后更新
    local leftSide = depth -- 对于第一侧,乌龟前进到完整深度
    local top = width - 1 -- 转弯并前进到完整的宽度-1,因为它位于第一行上
    local rightSide = depth -1 -- 转弯并回来深度,相同的路线
    local bottom = width -2 -- 转弯并前进宽度-2,已经接触过第一个和最后一个空间

    while moving do
        for i = 1, leftSide do
    turtle.forward() --向前移动一个空间
        end
    turtle.turnRight()

        for i = 1, top do
    turtle.forward()
        end
    turtle.turnRight()

        for i = 1, rightSide do
    turtle.forward()
        end
    turtle.turnRight()

        for i = 1, bottom do
    turtle.forward()
        end
    turtle.turnRight()

    -- 所有边都减去2,因为已经触摸了外部空间,来描述网格的下一层
    leftSide = leftSide -2
    top = top -2
    rightSide = rightSide -2
    bottom = bottom -2

        if (leftSide <= 0 and top <= 0 and rightSide <= 0 and bottom <= 0) then
    moving = false
        end

    end

end

任何帮助或建设性的评论都将不胜感激。

点赞
用户2858170
用户2858170

如果要触及网格中的每个点,没有比从一个点移动到另一个点更有效的方法,只触摸每个点一次。这就是你所做的。

您可以以螺旋状或按行或列的方式或这两种方式的混合方式进行操作。这并不重要,因为移动次数始终相同。

唯一的区别在于您的终点在哪里。

2021-03-27 19:08:33
用户1847592
用户1847592
# 将处于边缘的方块向两侧移动

## 函数 `MoveSides(depth, width)`

- 参数 `depth`:数字类型,代表从当前位置前进多少格。
- 参数 `width`:数字类型,代表需要移动多少次。

```lua
function MoveSides(depth, width)
   for i = 1, depth do
      turtle.forward() -- 前进一个空位
   end
   turtle.turnRight()
   if width > 1 then
      return MoveSides(width - 1, depth)
   end
end
2021-03-27 22:57:01
用户1856087
用户1856087
## 函数 `MoveSides(depth, width)`

该解决方案基本与Egor的递归算法相同,但没有递归调用。

function MoveSides(depth, width)
  current = depth
  other = width
  while current > 1 do
    for i = 1, current do
      turtle.forward()
    end
    turtle.turnRight()
    helper = current
    current = other -1
    other = helper
  end
end
2021-03-28 16:23:44