Skip to content

Instantly share code, notes, and snippets.

@AseedUsmani
Last active January 13, 2018 18:39
Show Gist options
  • Save AseedUsmani/8ff0bb3696c49ed2d08f0e041296af1a to your computer and use it in GitHub Desktop.
Save AseedUsmani/8ff0bb3696c49ed2d08f0e041296af1a to your computer and use it in GitHub Desktop.
public class Solution {
int maxSize;
int size;
int officeX;
int officeY;
public int calculate(ArrayList<Integer> x, ArrayList<Integer> y, int officeX, int officeY, int homeX, int homeY) {
size=x.size();
this.officeX=officeX;
this.officeY=officeY;
//intialize maxSize with any arbitrary path
//from office to 1st customer
maxSize=Math.abs(x.get(0)-officeX)+Math.abs(y.get(0)-officeY)
//each customer
for(int i=1; i<size; i++) maxSize+=Math.abs(x.get(i)-x.get(i-1)) + Math.abs(y.get(i))=y.get((i-1));
//home
maxSize+=Math.abs(homeX-x.get(size))+Math.abs(homeY-y.get(size));
permute(x, y, -1, new ArrayList<Integer>(), 0);
return maxSize;
}
public void permute(ArrayList<Integer> x, ArrayList<Integer> y, int index, ArrayList<Integer> temp, int currentSize) {
//add index to temp
if(index!=-1) temp.add(index);
//update currentSize
//if 1st customer is visited, temp.size()==1
if(temp.size==1) currentSize+=Math.abs(x.get(index)-officeX)+Math.abs(y.get(index)-officeY);
else currentSize+=Math.abs(x.get(index)-x.get(temp.get(index-1))+Math.abs(y.get(index)-y.get(temp.get(index-1));
if(currentSize>maxSize) return; //stop this way if length exceeds
//when all customers visited
if(temp.size()==x.size) {
//add distance to home
currentSize+=Math.abs(homeX-x.get(index))+Math.abs(homeY-y.get(index));
if(currentSize<maxSize) maxSize=currentSize;
return;
}
for(int i=0; i<A.size(); i++) {
if(!temp.contains(i)) {
permute(x, y, i, new ArrayList<Integer>(temp));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment