如果使用網格和遞歸,可以避免實際使用循環。
喜歡的東西
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;
}
打印(按照相反的順序,以避免創建座標列表)
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
22ms是相當不錯,給你一些I/O你使用。首先,你有沒有你用來完成任務的代碼?其次,你有更大的比例 - 2000x2000,20000x20000等嗎? – Makoto 2013-03-17 03:18:14
也許你應該發佈代碼? – 2013-03-17 03:18:49