繁体   English   中英

计算矩阵中的最短距离

[英]Compute the shortest distance in a matrix

字符矩阵如下:

#########
#P......#
####..###
##P....##
#.......#
#########

如何找到P和P之间的最短距离? 距离定义为从P移到P时的总步数。允许垂直或水平移动1步。 在矩阵中,“#”代表您无法克服的障碍“。”。 代表您可以通过的开放块。

通过简单地将矩阵从P到D进行DFS处理,很容易找到距离。但是,有没有更有效的方法来解决这个问题?

您可以确定指向目标的方向,并始终开始在该方向上寻找路径。 对于给定的简单矩阵,递归解决方案将立即找到路径,而不会走出第一步。 对于更复杂的矩阵,当然可以愚弄死胡同,因此采用并行方法可能会更好。

这是递归方法在C#中的样子:

public static int Distance(string[] matrix, int x, int y, int targetX, int targetY, int fromX, int fromY) {
  // show where we are
  Console.WriteLine(x + ", " + y);
  // check for target
  if (x == targetX && y == targetY) return 0;
  // determine valid moves
  List<Point> move = new List<Point> {
    new Point(-1, 0),
    new Point(1, 0),
    new Point(0, -1),
    new Point(0, 1),
  };
  move = move.Where(t => x + t.X != fromX || y + t.Y != fromY).ToList();
  move = move.Where(t => matrix[y + t.Y][x + t.X] != '#').ToList();
  // give up if we are in a dead end
  if (move.Count == 0) return 1000;
  // calculate direction towards target
  double dirX = (targetX - x);
  double dirY = (targetY - y);
  double distance = Math.Sqrt(dirX * dirX + dirY * dirY);
  dirX /= distance;
  dirY /= distance;
  // put moves towards the target first
  move = move.OrderBy(t => Math.Abs(t.X - dirX) + Math.Abs(t.Y - dirY)).ToList();
  // look for paths
  foreach (Point p in move) {
    int d = Distance(matrix, x + p.X, y + p.Y, targetX, targetY, x, y) + 1;
    if (d < 1000) return d;
  }
  return 1000;
}

主要:

string[] matrix = new string[]{
  "#########",
  "#P......#",
  "####..###",
  "##P....##",
  "#.......#",
  "#########"
};

// find starting and ending points
List<Point> p = new List<Point>();
for (int y=0;y<matrix.Length;y++) {
  for (int x=0;x<matrix[y].Length;x++) {
    if (matrix[y][x] == 'P') {
      p.Add(new Point(x,y));
    }
  }
}

// get distance
int d = Distance(matrix, p[0].X, p[0].Y, p[1].X, p[1].Y, -1, -1);
Console.WriteLine(d);

输出:

1, 1
2, 1
3, 1
4, 1
4, 2
4, 3
3, 3
2, 3
7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM