问题描述
我有一个由直角坐标系上四个角定义的矩形。
矩形由大小相同的单元格组成。
I have a rectangle defined by its four corners on a Cartesian coordinate system.The rectangle consist of identically sized cells.
给出一个角单元作为起点和方向(沿x轴或y轴)如何以蛇状图案遍历此网格?
Given one of the corner cells as a starting point and a direction (either along x or y axis) how can I traverse this grid in snake like pattern?
例如,此处(x4,y4)是起始单元格,方向定义为沿x轴。蓝线描述了所需的路径。
For example, here (x4, y4) is the starting cell and direction is defined to be along the x axis. Blue line depicts the desired path.
谢谢!
推荐答案
尝试4对点,以找到定义该框的相对点。然后,您将获得一个起点和一个对点。在您的情况下,followAlongX将作为输入,因此不需要测试方向,但是我添加了经典的决策文本。
Try the 4 pair of points to find the opposite point that defines the box. Then you have a Start and an Opposite pair of points. In your case, followAlongX will be an input so it's not needed to test the direction but I added a classic decision text otherwise.
最后,尝试类似(Java ,用记事本编写,未经测试):
In the end, try something like (Java, written in Notepad, not tested):
int stepY, stepX, yMin, yMax, yOpposite, yStart, xMin, xMax, xOpposite, xStart;
if (yOpposite > yStart) {
stepY = 1;
yMin = yStart;
yMax = yOpposite;
}
else {
stepY = -1;
yMax = yStart;
yMin = yOpposite;
}
if (xOpposite > xStart) {
stepX = -1;
xMin = xStart;
xMax = xOpposite;
}
else {
stepX = 1;
xMin = xOpposite;
xMax = xStart;
}
// boolean followAlongX = false;
// if (xMax-xMin>yMax-yMin) {
// loopOnX = true;
// }
List<Points> path = new ArrayList<>();
if (followAlongX) {
for (int i=yMin; i!=yMax; i+=stepY) {
for (int j=xmin; j!=xmax; j+=stepX) {
path.add(new Point(i,j));
}
stepX = -stepX;
int temp = xMin;
xMin = xMax;
xMax = temp;
}
}
else {
for (int j=xmin; j!=xmax; j+=stepX) {
for (int i=yMin; i!=yMax; i+=stepY) {
path.add(new Point(i,j));
}
stepY = -stepY;
int temp = yMin;
yMin = yMax;
yMax = temp;
}
}
return path.toArray(new Point[path.size()]);
这篇关于以蛇状图案遍历网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!