题解 | #迷宫问题#

迷宫问题

http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

public class Main{
    public static int[] dx={1,-1,0,0};
    public static int[] dy={0,0,1,-1};
    public static List<String> ans=new ArrayList<>();
    
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        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();
            }
        }
        route(map,0,0);        
    }
    //DFS
    public static void route(int[][] map,int i,int j){
        //如果移动到出口,直接输出当前路径并返回
        if(i==map.length-1&&j==map[0].length-1){
            for(String temp:ans){
                System.out.println(temp);
            }
            System.out.println("("+Integer.toString(i)+","+Integer.toString(j)+")");
            return;
        }
        //如果遇到墙壁或者走过的路 返回
        if(map[i][j]==1||map[i][j]==2)return;
        //否则当前位置为0可以移动,添加当前坐标
        ans.add("("+Integer.toString(i)+","+Integer.toString(j)+")");
        //标记走过的路
        map[i][j]=2;
        //下上右左顺序查找下一次移动位置
        for(int move=0;move<4;move++){
            i+=dx[move];
            j+=dy[move];
            //在迷宫范围内才进行查找
            if(i<map.length&&i>=0&&j<map[0].length&&j>=0){
                route(map,i,j);
            }
            //位置回退
            i-=dx[move];
            j-=dy[move];
            
        }
        //坐标回退
        ans.remove(ans.size()-1);
        return;
        
    }
}
全部评论

相关推荐

烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
12-20 13:19
已编辑
曲阜师范大学 Java
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务