java的线路求解问题
我想实现一个线路求解的方法,但是一直不知道怎么写!每次递归都堆溢出错误!求解
假如我有一个
Map<String,String> map = new HashMap<String,String>();
map.put("1","3,4");
map.put("2","3,4");
map.put("3","1,2,4");
map.put("4","1,2,3");
上面的初始值每个key相当于地铁的一个站,而对应的value值表示这个站所能到达的其他站(就比如1这个站能到3和4两个站),我现在想求出从1这个站到4这个站有几种方式,应该怎么写呢。
[解决办法]
你这个得好好设计下,不然会死循环吧。
[解决办法]
图的广度遍历和深度遍历,可以从这个思路来出发
[解决办法]
有向图的广度优先问题;
若是不能有重复节点,提供你一个思路:
findRoutes(起始节点, 终止节点, 当前线路) {
对起始节点的每个下一节点做如下操作: {
如果节点是终止节点, 则将节点添加到当前线路,加入线路的List中, continue;
如果节点已在当前线路中, continue;
否则, 将节点加入当前线路, 以节点为开始节点,终止节点不变,加入该节点后的线路为新的当前线路, 递归获得线路的List;
}
返回线路的List;
}
class Route {
private List<String> route;
public Route() {
route = new ArrayList<String>();
}
public List<String> getRoute() {
return route;
}
public int length() {
return this.route.size();
}
public void addStop(String stop) {
route.add(stop);
}
public boolean containsStop(String stop) {
return route.contains(stop) ? true : false;
}
public Route copyRoute() {
Route copy = new Route();
for (String stop : route)
copy.addStop(stop);
return copy;
}
public void printRoute() {
System.out.println("----------");
System.out.print("Route length: " + route.size() + "; ");
for (int i = 0; i < route.size(); i++) {
System.out.print(route.get(i));
if (i != route.size() - 1)
System.out.print("-->");
}
}
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "3,4");
map.put("2", "3,4");
map.put("3", "1,2,4");
map.put("4", "1,2,3");
Map<String, String[]> newMap = new HashMap<String, String[]>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
String[] stops = map.get(key).split(",");
newMap.put(key, stops);
}
String start = "1";
String end = "4";
Route route = new Route();
route.addStop(start);
List<Route> routeList = findRoute(newMap, start, end, route);
for (Route finalRoute : routeList) {
finalRoute.printRoute();
}
}
public static List<Route> findRoute(Map<String, String[]> map, String start, String end, Route route) {
List<Route> routeList = new ArrayList<Route>();
String[] stops = map.get(start);
for (String nextStop : stops) {
if (nextStop.equals(end)) {
Route temp = route.copyRoute();
temp.addStop(nextStop);
routeList.add(temp);
continue;
} else if (route.containsStop(nextStop)) {
continue;
} else {
Route temp = route.copyRoute();
temp.addStop(nextStop);
List<Route> subRouteList = findRoute(map, nextStop, end, temp);
for (Route subRoute : subRouteList) {
routeList.add(subRoute);
}
}
}
return routeList;
}