December 23, 2018

PipePuzzle in java

Solution for pipe puzzle in java


public class PipePuzzle {

private String [] pipes;
int x;
int y;
private boolean [][] filled = new boolean[20][20];
private int dirs[][] = {{-1,0},{0,1},{1,0},{0,-1}};
public int longest(String[] pipes){
this.pipes = pipes;
int[]values = findSource(this.pipes);
//System.out.println(java.util.Arrays.toString(values));
return maxflow(values[0],values[1],values[2]);
}

public int maxflow(int i, int j, int direction){
int ii = i + dirs[direction][0];
int jj = j + dirs[direction][1];
System.out.println(ii+" "+jj);
int sum = 0;
if(ii<0 || jj < 0 || ii >= x || jj >= y||(pipes[ii].charAt(jj) != '+' && filled[ii][jj]))
return 0;
filled[i][j] = true;
if(pipes[ii].charAt(jj) == '-' || pipes[ii].charAt(jj) == '+'){
sum = 1+maxflow(ii,jj,direction);
}
else{
int left = 1+maxflow(ii,jj,(direction+1)%4);
int right = 1+maxflow(ii,jj,(direction+3)%4);
sum = Math.max(left,right);
}
filled[i][j] = false;
return sum;
}

public int[] findSource(String[]pipes){
x = pipes.length;
y = pipes[0].length();
int [] values = new int[3];
for(int i = 0; i < x; i++){
for(int j = 0; j< y; j++){
if(pipes[i].charAt(j) == 'N'){
values[2] = 0;
values[0] = i;
values[1] = j;
break;
}
else if(pipes[i].charAt(j) == 'E'){
values[2] = 1;
values[0] = i;
values[1] = j;
break;
}
else if(pipes[i].charAt(j) == 'S'){
values[2] = 2;
values[0] = i;
values[1] = j;
break;
}
else if(pipes[i].charAt(j) == 'W'){
values[2] = 3;
values[0] = i;
values[1] = j;
break;
}

}
}
return values;
}

static String [] test1 = {"LL-L-",
"L+L+L",
"--NL-",
"L+--L",
"LL+L-"};
static String[]test2 = {"ELLL",
"LLLL",
"LLLL",
"LLLL"};
public static void main(String[] args) {
PipePuzzle p = new PipePuzzle();
System.out.println(p.longest(test1));

}

}

The Girl in the room 105 - Book by chetan bhagat Buy!!!

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments