I have a two dimensional boolean array:
boolean [][] field = new boolean[7][11];
What I want to do, is check if there is a valid “path” from field[0][0] to field[7][11].
For example, this would be a valid path from start to end:
0 = false, 1 = true
1 1 0 0 0
0 1 0 0 0
1 1 0 0 0
1 0 0 0 0
1 1 1 1 1
We can connect from 0,0 to 4,4 with true values.
Example for invalid path:
1 1 0 0 0
0 1 0 0 0
1 0 0 0 0
1 0 0 0 0
1 1 1 1 1
We cannot connect fro 0,0 to 4,4. (only vertical and horizontal values are a valid path, not diagonal)
I think the best way to approach this is with recursion. Start from 0,0, check the neighbours for “true” and move on to it if so. Then again check the neighbours. If all neighbours are false, move back and find another path.
What would be the best way to approach this?
EDIT :
This is what I have so far.
The algorithm prints out exactly the correct path, but my return value is not always right.
Can anyone see where the error is?
static boolean isValidPath(boolean [][] field, int i, int j, int previ, int prevj) {
if(i >= field.length && j >= field[0].length) return true;
if(field[i][j] == true) {
System.out.println("Valid i: " + i + ", j: " + j);
if(i + 1 < field.length && i + 1 != previ) isValidPath(field, i + 1, j, i, j);
if(j + 1 < field[0].length && j + 1 != prevj) isValidPath(field, i, j + 1, i, j);
if(i - 1 >= 0 && i - 1 != previ) isValidPath(field, i - 1, j, i, j);
if(j - 1 >= 0 && j - 1 != prevj) isValidPath(field, i, j - 1, i, j);
return true;
} else return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean[][] field = new boolean[][] { { true, true, false, false, false},
{ false, true, false, false, false},
{ true, true, false, false, false},
{ true, false, false, false, false},
{ true, true, true, true, true }};
System.out.println("Is this path valid: " + isValidPath(field, 0, 0, 0, 0));
}
This is the output:
Valid i: 0, j: 0
Valid i: 0, j: 1
Valid i: 1, j: 1
Valid i: 2, j: 1
Valid i: 2, j: 0
Valid i: 3, j: 0
Valid i: 4, j: 0
Valid i: 4, j: 1
Valid i: 4, j: 2
Valid i: 4, j: 3
Valid i: 4, j: 4
Is this path valid: true
As you can see, the algorithm runs over the whole array, and prints out the valid path.
But if I for example change the value in [4][4] to false, the result is still true.
I dont really know where to return false and true.
What you have here is simply a graph presented in a more non-cannonical way. Any type of graph search will do to solve your problem. I suggest you use either BFS or DFS. Actually DFS usually is implemented using recursion so,yes you can solve this problem using recursion.