find Shortest Path With Greedy Approach - Java java.lang

Java examples for java.lang:Math Algorithm

Description

find Shortest Path With Greedy Approach

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static List<Integer> findShortestPathWithGreedyApproach(
            final int start, final int[][] distances) {
        final List<Integer> locations = new ArrayList<>();
        locations.add(start);//from   w  ww.  j  a  va 2s . co  m

        int curr = start;
        while (locations.size() < distances[0].length) {
            int next = 0;
            int nextDist = Integer.MAX_VALUE;
            for (int i = 0; i < distances[0].length; i++) {
                if (!locations.contains(i) && distances[curr][i] < nextDist) {
                    next = i;
                    nextDist = distances[curr][i];
                }
            }
            locations.add(next);
        }
        return locations;
    }
}

Related Tutorials