题解 | #字符串排序#

迷宫问题

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

简单的dfs,用了treemap以自动排序。

import java.util.*;

public class Test43 {
    static int[][] maze;
    static int y;
    static int x;
    static TreeMap<Integer, List<String>> result = new TreeMap<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            y = sc.nextInt();
            x = sc.nextInt();
            maze = new int[y][x];
            for (int i = 0; i < y; i++) {
                for (int j = 0; j < x; j++) {
                    maze[i][j] = sc.nextInt();
                }
            }
            List<String> list = new ArrayList<>();
            list.add("(0,0)");
            getResult(0, 0, 0, list);
            for (Map.Entry<Integer, List<String>> map : result.entrySet()) {
                for (String s : map.getValue()) {
                    System.out.println(s);
                }
                break;
            }
        }
    }

    public static void getResult(int count, int y2, int x2, List<String> list) {
        if (y2 == y - 1 && x2 == x - 1) {
            result.put(count, list);
            return;
        } else {
            if (y2 + 1 < y && maze[y2 + 1][x2] == 0 && !list.contains("(" + (y2 + 1) + "," + x2 + ")")) {
                List<String> list2 = new ArrayList<>(list);
                list2.add("(" + (y2 + 1) + "," + x2 + ")");
                getResult(count++, y2 + 1, x2, list2);
            }
            if (y2 - 1 >= 0 && maze[y2 - 1][x2] == 0 && !list.contains("(" + (y2 - 1) + "," + x2 + ")")) {
                List<String> list2 = new ArrayList<>(list);
                list2.add("(" + (y2 - 1) + "," + x2 + ")");
                getResult(count++, y2 - 1, x2, list2);
            }
            if (x2 + 1 < x && maze[y2][x2 + 1] == 0 && !list.contains("(" + y2 + "," + (x2 + 1) + ")")) {
                List<String> list2 = new ArrayList<>(list);
                list2.add("(" + y2 + "," + (x2 + 1) + ")");
                getResult(count++, y2, x2 + 1, list2);
            }
            if (x2 - 1 >= 0 && maze[y2][x2 - 1] == 0 && !list.contains("(" + y2 + "," + (x2 - 1) + ")")) {
                List<String> list2 = new ArrayList<>(list);
                list2.add("(" + y2 + "," + (x2 - 1) + ")");
                getResult(count++, y2, x2 - 1, list2);
            }
            return;
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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