与图片一样,我给出了(x,y)网格中每条线(线)的起点和终点(我可能需要找到更多的线路。)我需要什么做的是找到彼此不相交的每根导线的最小路径(如果没有找到可能的解决方案那么它是一个例外。) 我可以找到从单线到点的所有可能路径,但很难考虑多条路径。
public static PriorityQueue<Path> pathesOfAWire(Chip chip, Wire w) {
boolean[][] isVisited = new boolean[chip.dim.width][chip.dim.height];
Path path = new Path(w);
PriorityQueue<Path> ans = new PriorityQueue<>((x, y) -> x.length() -
y.length());
addAllPathesUtil(chip, w.from, w.to, isVisited, path, ans);
return ans;
}
private static void addAllPathesUtil(Chip chip, Coord from, Coord to,
boolean[][] isVisited, Path p,
PriorityQueue<Path> ans) {
isVisited[from.x][from.y] = true;
if (from.equals(to)) {
Path np = new Path(p.wire);
for (int i = 1; i < p.length(); i++)
np.add(p.get(i));
ans.offer(np);
}
for (Coord neighbors : from.neighbors(chip.dim)) {
if (!isVisited[neighbors.x][neighbors.y] &&
(chip.isFree(neighbors) || neighbors.equals(to))) {
p.add(neighbors);
addAllPathesUtil(chip, neighbors, to, isVisited, p, ans);
p.remove(neighbors);
}
}
isVisited[from.x][from.y] = false;
}
这是我的代码只有一条路径(一个起点和一个终点。)
public static void helper(Chip chip, Coord[] from, Coord[] to,
boolean[][] isVisited, Path[] p,
Map<Integer, Path> ans) {
for (int i = 0; i < from.length; i++) {
isVisited[from[i].x][from[i].y] = true;
}
boolean completed = true;
for (int i = 0; i < to.length; i++) {
if (!from[i].equals(to[i])) {
completed = false;
}
}
for (int i = 0; i < p.length; i++) {
System.out.println("Wire " + (i + 1) + " : " + p[i]);
}
if (completed) {
System.out.println("hihihi");
for (Path a : p) {
Path np = new Path(a.wire);
for (int i = 1; i < a.length(); i++)
np.add(a.get(i));
ans.put(np.wire.wireId, np);
}
}
for (int i = 0; i < from.length; i++) {
for (Coord neighbors : from[i].neighbors(chip.dim)) {
if (!isVisited[neighbors.x][neighbors.y] &&
(chip.isFree(neighbors) || neighbors.equals(to[i]))) {
p[i].add(neighbors);
from[i] = neighbors;
helper(chip, from, to, isVisited, p, ans);
p[i].remove(neighbors);
}
}
}
for (int i = 0; i < from.length; i++) {
isVisited[from[i].x][from[i].y] = false;
}
}
考虑到单线的算法,我尝试对多条线应用相同的逻辑,但没有做到。我需要帮助来改进我的算法或一些提示如何以不同的方式解决这个问题。 芯片是具有电线和自由单元的障碍和信息的网格。 Map是Integer(线程ID)和路径之间的关联 感谢