不是一个解决方案,但也许你可以进一步思考这个想法。问题是您还需要计算获得所有路径的最长可能路径。对于一般图,最长路径问题是 NP 完全的,因此即使对于相对较小的图(8x8 和更大),它也会得到很长的时间。
想象一下,起始顶点位于矩阵的左上角,而结束顶点位于矩阵的右下角。
- 对于 1x2 矩阵,只有 1 个可能的路径
- 2x2 矩阵 => 2***1** 路径 => 2
- 3x2 矩阵 => 2***2** 路径 => 4
- 3x3 矩阵 => 2***4** + 2*2 路径 => 12
- 3x4 矩阵 => 2***12** + 12 + 2 条路径 => 38
每次我结合当前路径数的先前计算的结果。这样的平面图可能有一个接近的公式,也许甚至有很多理论,但我对此太愚蠢了......
您可以使用以下 Java(对不起,我不是 c++ 专家:-/)片段来计算更大矩阵的可能路径:
public static void main(String[] args) {
new Main(3, 2).start();
}
int xSize;
int ySize;
boolean visited[][];
public Main(int maxX, int maxY) {
xSize = maxX;
ySize = maxY;
visited = new boolean[xSize][ySize];
}
public void start() {
// path starts in the top left corner
int paths = nextCell(0, 0);
System.out.println(paths);
}
public int nextCell(int x, int y) {
// path should end in the lower right corner
if (x == xSize - 1 && y == ySize - 1)
return 1;
if (x < 0 || y < 0 || x >= xSize || y >= ySize || visited[x][y]) {
return 0;
}
visited[x][y] = true;
int c = 0;
c += nextCell(x + 1, y);
c += nextCell(x - 1, y);
c += nextCell(x, y + 1);
c += nextCell(x, y - 1);
visited[x][y] = false;
return c;
}
=>
- 4x4 => 184
- 5x5 => 8512
- 6x6 => 1262816
- 7x7(即使是这个简单的案例也需要很多时间!)=> 575780564
这意味着您可以(仅在理论上)计算从 MxM 矩阵的任何位置到右下角的所有可能路径,然后使用该矩阵快速查找路径数。动态编程(使用以前的计算结果)可以加快速度。