从(0,0)开始,四个方向遍历,深度优先搜索,找到一条路径。
import java.util.Scanner;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n = sc.nextInt();
int m = sc.nextInt();
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = sc.nextInt();
}
}
ArrayList<int[]> path = new ArrayList<>();//路径
dfs(map, 0, 0, path);
for (int[] num : path) {
System.out.println("(" + num[0] + "," + num[1] + ")");
}
}
public static boolean dfs(int[][] map, int i, int j, ArrayList<int[]> path) {
map[i][j] = 1;
path.add(new int[] {i, j});
if (i == map.length - 1 && j == map[0].length - 1) return true;
if (i - 1 >= 0 && map[i - 1][j] != 1) { //上
if(dfs(map, i - 1, j, path)) return true;
}
if (i + 1 < map.length && map[i + 1][j] != 1) {//下
if(dfs(map, i + 1, j, path)) return true;
}
if (j - 1 >= 0 && map[i][j - 1] != 1) { //左
if(dfs(map, i, j - 1, path)) return true;
}
if (j + 1 < map[0].length && map[i][j + 1] != 1) { //右
if(dfs(map, i, j + 1, path)) return true;
}
map[i][j] = 0;
path.remove(path.size()-1);
return false;
}
}