地下迷宫java题解

地下迷宫

http://www.nowcoder.com/questionTerminal/571cfbe764824f03b5c0bfd2eb0a8ddf

import java.util.*;

public class Main {
    static boolean flag = false;
    static int n, m, p;
    static String path = "";
    static int maxRemain;
    static int[][] map;
    static LinkedList<String> list = new LinkedList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            n = sc.nextInt();
            m = sc.nextInt();
            p = sc.nextInt();
            map = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    map[i][j] = sc.nextInt();
                }
            }
            search(0, 0, p);
            if(flag == true) {
                System.out.println(path);
            } else {
                System.out.println("Can not escape!");
            }
        }
    }

    private static void search(int i, int j, int energy) {
        if (i < 0 || i >= n || j < 0 || j >= m || energy < 0 || map[i][j] != 1) {
            return;
        } else {
            map[i][j] = 2;
            list.add("[" + i + "," + j + "]");
            if (i == 0 && j == m - 1) {
                if (energy >= maxRemain) {
                    maxRemain = energy;
                    updatePath();
                }
                map[i][j] = 1;
                list.removeLast();
                flag = true;
                return;
            }
        }
        search(i - 1, j, energy - 3);
        search(i + 1, j, energy);
        search(i, j - 1, energy - 1);
        search(i, j + 1, energy - 1);
        map[i][j] = 1;
        list.removeLast();
    }

    private static void updatePath() {
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            sb.append(str + ",");
        }
        path = sb.deleteCharAt(sb.length() - 1).toString();
    }
}
全部评论
x+1为什么是下去,这不是上去吗
点赞 回复 分享
发布于 2020-09-19 17:52

相关推荐

02-08 20:56
已编辑
南京工业大学 Java
在等offer的比尔很洒脱:我也是在实习,项目先不说,感觉有点点小熟悉,但是我有点疑问,这第一个实习,公司真的让实习生去部署搭建和引入mq之类的吗,是不是有点过于信任了,我实习过的两个公司都是人家正式早搭好了,根本摸不到部署搭建的
点赞 评论 收藏
分享
2024-12-21 01:36
电子科技大学 Java
牛客850385388号:员工福利查看图片
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务