题解 | #迷宫问题#

迷宫问题

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) { 
            String[] NM = in.nextLine().split(" ");
            int[] nm = new int[2];
            nm[0] = Integer.parseInt(NM[0]);
            nm[1] = Integer.parseInt(NM[1]);
            int[][] MG = new int[nm[1]][nm[0]];
            for (int m = 0;m<nm[0];m++){
                String[] cc = in.nextLine().split(" ");
                for (int n = 0;n<nm[1];n++){
                    MG[n][m] = Integer.parseInt(cc[n]);
                }
            }
            List<int[]> GG = new ArrayList<>();
            List<int[]> res = DG(0,0,MG,GG,0,0,nm[1],nm[0]);
            System.out.println("(0,0)");
            for (int i = res.size()-1;i>=0;i--){
                System.out.println("("+res.get(i)[1]+","+res.get(i)[0]+")");
            }
        }
    }
    public static List<int[]> DG(int n,int m,int[][] MG,List<int[]> list,int ln,int lm,int nMax,int mMax){
        int chang = list.size();
        //下到
        if (n+1==nMax-1&&m==mMax-1) {
            list.add(new int[]{n+1,m});
            return list;
        }
        //右到
        if (n==nMax-1&&m+1==mMax-1){
            list.add(new int[]{n,m+1});
            return list;
        }
        //下未到
        if (n+1<nMax&&n+1!=ln&&MG[n+1][m]==0){
            list = DG(n+1,m,MG,list,n,m,nMax,mMax);
            if (chang!=list.size()) {
                list.add(new int[]{n+1,m});
                return list;
            }
        }
        //右未到
        if (m+1<mMax&&m+1!=lm&&MG[n][m+1]==0){
            list = DG(n,m+1,MG,list,n,m,nMax,mMax);
            if (chang!=list.size()) {
                list.add(new int[]{n,m+1});
                return list;
            }
        }
        //左
        if (m-1>=0&&m-1!=lm&&MG[n][m-1]==0){
            list = DG(n,m-1,MG,list,n,m,nMax,mMax);
            if (chang!=list.size()) {
                list.add(new int[]{n,m-1});
                return list;
            }
        }
        //右
        if (n-1>=0&&n-1!=ln&&MG[n-1][m]==0){
            list = DG(n-1,m,MG,list,n,m,nMax,mMax);
            if (chang!=list.size()) {
                list.add(new int[]{n-1,m});
                return list;
            }
        }
        return list;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务