首页 > 解决方案 > 蛮力耗尽内存空间

问题描述

我正忙于创建一个蛮力 TSP 算法,该程序当前工作并计算我输入的最短路径。遗憾的是,我可以使用的最大节点数是 10,这是因为每当我更高时,我都会得到:“Java.lang.OutofMemoryError: Java heap space”。我一直在尝试优化代码,但结果可以忽略不计。如何进一步优化我的代码,以便在运行算法时使用更多节点?

这是我的代码:

import com.sybrand.TSP.*;
import java.util.*;

public class BruteForce extends TSP_Algorithm {

    private ArrayList<Coordinate> sortedCoords = new ArrayList<>();
    ArrayList<Coordinate> coords = new ArrayList<>();
    ArrayList<Coordinate> shortestRoute;

    public BruteForce(ArrayList<Coordinate> coords) {
        sortedCoords.addAll(coords);
        permutation(sortedCoords);
    }

    public void permutation(ArrayList<Coordinate> nums) {
        List<List<Coordinate>> accum = new ArrayList<>();
        permutation(accum, Collections.emptyList(), nums);
        float shortestDistance = 0.0f;
        for (List<Coordinate> routeOption: accum) {
            Path calcDistance = new Path((ArrayList<Coordinate>) routeOption);
            if (shortestDistance == 0.0f || calcDistance.getDistance() < shortestDistance) {
                shortestDistance = calcDistance.getDistance();
                this.shortestRoute = (ArrayList<Coordinate>) routeOption;
            }
        }
    }

    private static void permutation(List<List<Coordinate>> accum, List<Coordinate> prefix, List<Coordinate> nums) {
        int n = nums.size();
        if (n == 0) {
            accum.add(prefix);
        } else {
            for (int i = 0; i < n; ++i) {
                List<Coordinate> newPrefix = new ArrayList<>(prefix);
                newPrefix.add(nums.get(i));
                List<Coordinate> numsLeft = new ArrayList<>(nums);
                numsLeft.remove(i);
                permutation(accum, newPrefix, numsLeft);
            }
        }
    }

    public ArrayList<Coordinate> getSortedCoordinates() {
        return shortestRoute;
    }
}

标签: javabrute-force

解决方案


推荐阅读