阿里最短派送路线测试题

问题描述:

阿里最短派送路线测试题_第1张图片

 

 解决思路:

        将所有路径进行全排列,然后依次求出路径的大小,最后比较最小值,则得出最终结果

缺点:复杂度很高,不知道是否满足运行时间的条件

代码如下:

package whg.org;
import java.util.*;
import java.lang.*;
public class Whg {
    public static ArrayList arr = new ArrayList();
    public static ArrayList dat = new ArrayList();
    public static int total = 0;
    public static void swap(String[] str, int i, int j)
    {
        String temp = new String();
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    public static void arrange (String[] str, int st, int len)
    {
        if (st == len - 1)
        {
            String val="";
            for (int i = 0; i < len; i ++)
            {

                val += str[i];
                if(i == len-1){
                    continue;
                }
                val = val +"-";
            }
            arr.add(val);
            total++;
        }
        else
        {
            for (int i = st; i < len; i ++)
            {
                swap(str, st, i);
                arrange(str, st + 1, len);
                swap(str, st, i);
            }
        }
    }
    /*
        返回的是两个点之间的距离
     */
    public static int calTwoPoint(String x,String y){
        String [] _x = x.split(",");
        String [] _y = y.split(",");
        return Math.abs(Integer.valueOf(_x[0])-Integer.valueOf(_y[0]))+Math.abs(Integer.valueOf(_x[1])-Integer.valueOf(_y[1]));
    }

    public static void calculate(ArrayList _dat,HashMap _hm){
        for (int i = 0; i < _dat.size(); i++) { //分别计算每个距离
            String _buf = _dat.get(i);
            //计算距离
            int sum = 0;
            String []_ar = _buf.split("-");
            for (int j = 0; j < _ar.length-1; j++) {
                sum = sum + calTwoPoint(_hm.get(_ar[j]),_hm.get(_ar[j+1]));
            }
            sum = sum + calTwoPoint("0,0",_hm.get(_ar[0]));
            sum = sum + calTwoPoint("0,0",_hm.get(_ar[_ar.length-1]));
            dat.add(sum);
        }
        //输出最小
        System.out.println(Collections.min(dat));
    }
    public static void main(String[] args) {
        HashMap hm = new HashMap();
        Scanner input = new Scanner(System.in);
        int number = Integer.valueOf(input.nextLine());
        for (int i = 0; i < number; i++) {
            String v = input.nextLine();
            hm.put(String.valueOf(i+1),v);
        }
        String [] str = new String[number];
        for (int i = 0; i < number; i++) {
            str[i] = String.valueOf(i+1);
        }
        arrange(str, 0, str.length);
        calculate(arr,hm);
    }
}

测试结果:

阿里最短派送路线测试题_第2张图片

阿里最短派送路线测试题_第3张图片

你可能感兴趣的:(java,阿里测试,最短路径)