If you use a grid and recursion, you can avoid actually using a loop at all.
Something like
public static void main(String... ignored) {
search(2, 2, "..........\n" +
".########.\n" +
"...#......\n" +
"#####.####\n" +
"X.........\n");
}
public static boolean search(int x, int y, String grid) {
String[] rows = grid.split("\n");
char[][] grid2 = new char[rows.length][];
for (int i = 0; i < rows.length; i++) {
String row = rows[i];
grid2[i] = row.toCharArray();
}
return search(x, y, grid2);
}
public static boolean search(int x, int y, char[][] grid) {
if (x < 0 || x >= grid.length || y < 0 || y > grid[0].length)
return false;
char ch = grid[x][y];
if (ch == 'X') {
System.out.println("End " + x + ", " + y);
return true;
}
// - is been here before
// # is a wall.
if (ch == '-' || ch == '#') {
return false;
}
grid[x][y] = '-'; // been here before.
boolean found = search(x - 1, y, grid) || search(x + 1, y, grid)
|| search(x, y - 1, grid) || search(x, y + 1, grid);
grid[x][y] = ch;
if (found)
System.out.println("... " + x + ", " + y);
return found;
}
prints (in reverse order to avoid creating a list of co-ordinates)
End 4, 0
... 4, 1
... 4, 2
... 4, 3
... 4, 4
... 4, 5
... 3, 5
... 2, 5
... 2, 6
... 2, 7
... 2, 8
... 2, 9
... 1, 9
... 0, 9
... 0, 8
... 0, 7
... 0, 6
... 0, 5
... 0, 4
... 0, 3
... 0, 2
... 0, 1
... 0, 0
... 1, 0
... 2, 0
... 2, 1
... 2, 2