*...*..D .G..*..... **...**. .S....*. ........ ...G**.. ........ .G..*...
这是2d数组, 必须访问 S - Source D-Destination G-Point 。“。”自由路径 “ *” Block Paths 能帮我这是在Java中找到最短路径长度的有效算法吗, Only Horizontal and垂直运动是可能的
要查找start点到地图上所有其他点的最短距离,可以使用BFS。样例代码:
start
public void visit(String []map , Point start){ int []x = {0,0,1,-1};//This represent 4 directions right, left, down , up int []y = {1,-1,0,0}; LinkedList<Point> q = new LinkedList(); q.add(start); int n = map.length; int m = map[0].length(); int[][]dist = new int[n][m]; for(int []a : dist){ Arrays.fill(a,-1); } dist[start.x][start.y] = 0; while(!q.isEmpty()){ Point p = q.removeFirst(); for(int i = 0; i < 4; i++){ int a = p.x + x[i]; int b = p.y + y[i]; if(a >= 0 && b >= 0 && a < n && b < m && dist[a][b] == -1 && map[a].charAt(b) != '*' ){ dist[a][b] = 1 + dist[p.x][p.y]; q.add(new Point(a,b)); } } } }
问题的第二条路径实际上是旅行商问题,因此您需要从原始图转换为一个图only contains G,D and S points,weight该图的每个边的为shortest path between them in original path。从那时起,如果G的数量很小(小于17),则可以dynamic programming and bitmask用来解决问题。
only contains G,D and S points
weight
shortest path between them in original path
dynamic programming and bitmask