importjava.util.*;// 题目已经提示了 【迷宫只有一条通道】,则直接使用 DFS 找路径就行了,如不有多条路径找最短考虑使用 BFSpublicclassMain{publicstaticvoidmain(String[] args){
Scanner in =newScanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while(in.hasNextInt()){// 注意 while 处理多个 caseint n = in.nextInt();int m = in.nextInt();// 构造迷宫int[][] map =newint[n][m];for(int i =0; i < n; i++){for(int j =0; j < m; j++){
map[i][j]= in.nextInt();}}// 路径存储的数组
List<Pos> path =newArrayList<>();// DFS 搜索路径dfs(map,0,0, path);// 输出for(Pos p : path){
System.out.println("("+ p.x +","+ p.y +")");}}}// 返回值 标记是否找到可通行的路劲publicstatic boolean dfs(int[][] map,int x,int y, List<Pos> path){// 添加路径并标记已走
path.add(newPos(x, y));
map[x][y]=1;// 结束标志if(x == map.length -1&& y == map[0].length -1){returntrue;}// 向下能走时if(x +1< map.length && map[x +1][y]==0){if(dfs(map, x +1, y, path)){returntrue;}}// 向右能走时if(y +1< map[0].length && map[x][y +1]==0){if(dfs(map, x, y +1, path)){returntrue;}}// 向上能走时if(x -1>-1&& map[x -1][y]==0){if(dfs(map, x -1, y, path)){returntrue;}}// 向左能走时if(y -1>-1&& map[x][y -1]==0){if(dfs(map, x, y -1, path)){returntrue;}}// 回溯
path.remove(path.size()-1);
map[x][y]=0;returnfalse;}// 简单的位置类publicstaticclassPos{int x;int y;publicPos(int x,int y){this.x = x;this.y = y;}}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
法一:
1. 两个数组,一个存走过的路径,一个存地图
2. 如果合法再dfs
#includeusingnamespace std;int mp[11][11],
used[11][11];//mp数组存储地图,used数组存储当前该位置是否已经走过int n, m;constint dx[4]={1,-1,0,0}, dy[4]={0,0,1,-1};//dx和dy分别代表上下左右方向intisValid(int posx,int posy){if(posx >=0&& posx < n && posy >=0&& posy < m &&!used[posx][posy]&&!mp[posx][posy])return1;return0;}//判断当前位置是否合法,(1)必须在迷宫范围内,(2)当前位置不能是墙壁,(3)当前位置不能走过bool flag =true;voiddfs(int x,int y){if(!flag)return;//已经输出了路径,不再搜索//printf("%d %d\n",x,y);if(x == n -1&& y == m -1){//已到达终点就输出路径int i =0, j =0;do{
cout <<'('<< i <<','<< j <<')'<< endl;
used[i][j]=0;if(used[i][j +1]) j++;elseif(used[i +1][j])i++;elseif(used[i -1][j])i--;elseif(used[i][j -1])j--;}while(!(i == n -1&& j == m -1));//只要没到终点就继续输出
cout <<'('<< n -1<<','<< m -1<<')'<< endl;//输出终点
flag =false;}elsefor(int i =0; i <=3; i++){if(isValid(x + dx[i], y + dy[i])){//若下一步是合法的
used[x + dx[i]][y + dy[i]]=1;//搜索下一步的路径dfs(x + dx[i], y + dy[i]);
used[x + dx[i]][y + dy[i]]=0;}}}intmain(){while(~scanf("%d%d",&n,&m)){//输入地图规模
flag =true;memset(used,0,sizeof used);for(int i =0; i < n; i++)for(int j =0; j < m; j++)scanf("%d",&mp[i][j]);//读入地图
used[0][0]=1;dfs(0,0);}}