题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static class Pos{
int x;
int y;
Pos(int x,int y){
this.x=x;
this.y=y;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n=in.nextInt();
int m=in.nextInt();
int[][] a=new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[i][j]=in.nextInt();
}
}
List<Pos> list=new ArrayList<>();
dfs(a,0,0,list);
for(Pos pos:list){
System.out.println("("+pos.x+","+pos.y+")");
}
}
public static boolean dfs(int[][] a,int x,int y,List<Pos> list){
list.add(new Pos(x,y));
a[x][y]=1;
//终点
if(x==a.length-1 && y==a[0].length-1 ){
return true;
}
//向右能走
if(x+1<a.length && a[x+1][y]==0){
if(dfs(a,x+1,y,list))
return true;
}
//左
if(x-1>-1 && a[x-1][y]==0){
if(dfs(a,x-1,y,list))
return true;
}
//上
if(y+1<a[0].length && a[x][y+1]==0){
if(dfs(a,x,y+1,list))
return true;
}
//下
if(y-1>-1 && a[x][y-1]==0){
if(dfs(a,x,y-1,list))
return true;
}
list.remove(list.size()-1);
a[x][y]=0;
return false;
}
}


查看10道真题和解析