如果我从onClick收集了两个点并且它们作为索引或位置在网格上,我如何计算上,下,左和右的天气,不允许对角线到达另一点的最短路径?因此,如果我有pointA和pointB,并且B点试图在最短路径中到达pointA并且我会在每次移动后重新计算这个,因为pointA将在从B点移动之后移动。我开始写的是找到相邻的位置在没有对角线的点B附近所以边缘上的点显然会有较少的选项但是如何通过选择相邻的正方形确定正确的运动? pointB应该优先使用索引向上,向下,向左和向下移动吗?我从零开始索引,其11乘11格,所以11列。我刚才想到的是处理具有相同距离的选择,在它们之间随机选择。
0 1 2 3 4 ...
11 12 13 14 15 ...
22 23 24 25 16 ...
33 34 35 36 37 ...
etc...
我找到了我现在可以尝试选择最短路径的索引数组
Integer[] getAdjacentPositions(int position)
{
/*This will return integer array of positions that adjacent to position that is
pass through that are not diagonal.*/
Integer[] columnRow = new Integer[8];
int columns = 11;
int column = (position % columns);
int row = (position / columns);
int numberedges = 0;
Log.d(TAG, "position inside of isedgeitem is " + position );
Log.d(TAG, "row is " + row );
Log.d(TAG, "column is " + column );
for (int rowOffset = -1; rowOffset <= 1; rowOffset++)
{
final int actRow = row + rowOffset;
for (int columnOffset = -1; columnOffset <= 1; columnOffset++)
{
final int actColumn = column + columnOffset;
if (actRow >= 0 && actRow < 11 && actColumn >= 0 && actColumn < 11)
{
if (!isOneOfDiagonals(position, (actColumn + actRow * columns)))
{
columnRow[numberedges]= actColumn + actRow * columns;
numberedges++;
}
Log.d(TAG, " actColumn" + actColumn );
Log.d(TAG, " actRow" + actRow );
}
}
}
return columnRow;
}
现在如何处理这个Int索引数组以找到最短路径
shortestnextposition(Integer[] positions, int pointA )
{
return int position;
}
答案 0 :(得分:0)
如果我理解正确的问题:
最短路径的问题是你可以有不同的方式使用最短距离的移动次数。但是你可以在这个动作中编写一个偏好,例如,如果你必须从0到24,最短的距离是3,你有3种最短的方法:
我想你想使用第三种可能性?
为此,比较dX和dY并移动更大的维度,如果dX> dY,移动X,如果dY> dX,moveY
更新:试试这个
public static int[] shortestPath(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int[] path = new int[Math.abs(ax - bx) + Math.abs(ay - by) + 1];
for (int i = 0; i < path.length; i++)
path[i] = a = i == 0 ? a : getAdjacentInDirectionOf(x, a, b);
return path;
}
public static int getAdjacentInDirectionOf(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int dx = Math.abs(ax - bx), dy = Math.abs(ay - by);
if (dx >= dy) return (int) (ax + Math.signum(bx - ax) + ay * x);
else return (int) (ax + (ay + Math.signum(by - ay)) * x);
}
更新:替换之前的shortestPath()方法以避免第一种情况
public static int[] shortestPath(int x, int a, int b) {
int ax = a % x, ay = a / x, bx = b % x, by = b / x;
int[] path = new int[Math.abs(ax - bx) + Math.abs(ay - by)];
for (int i = 0; i < path.length; i++)
path[i] = a = getAdjacentInDirectionOf(x, a, b);
return path;
}