杭电1026_ Ignatius and the Princess I (BFS+模拟 或者 BFS+优先队列)——java

Problem Description
The Princess has been abducted by the BEelzebub feng5166, our hero Ignatius has to rescue our pretty Princess. Now he gets into feng5166's castle. The castle is a large labyrinth. To make the problem simply, we assume the labyrinth is a N*M two-dimensional array which left-top corner is (0,0) and right-bottom corner is (N-1,M-1). Ignatius enters at (0,0), and the door to feng5166's room is at (N-1,M-1), that is our target. There are some monsters in the castle, if Ignatius meet them, he has to kill them. Here is some rules:

1.Ignatius can only move in four directions(up, down, left, right), one step per second. A step is defined as follow: if current position is (x,y), after a step, Ignatius can only stand on (x-1,y), (x+1,y), (x,y-1) or (x,y+1).
2.The array is marked with some characters and numbers. We define them like this:
. : The place where Ignatius can walk on.
X : The place is a trap, Ignatius should not walk on it.
n : Here is a monster with n HP(1<=n<=9), if Ignatius walk on it, it takes him n seconds to kill the monster.

Your task is to give out the path which costs minimum seconds for Ignatius to reach target position. You may assume that the start position and the target position will never be a trap, and there will never be a monster at the start position.
 

Input
The input contains several test cases. Each test case starts with a line contains two numbers N and M(2<=N<=100,2<=M<=100) which indicate the size of the labyrinth. Then a N*M two-dimensional array follows, which describe the whole labyrinth. The input is terminated by the end of file. More details in the Sample Input.
 

Output
For each test case, you should output "God please help our poor hero." if Ignatius can't reach the target position, or you should output "It takes n seconds to reach the target position, let me show you the way."(n is the minimum seconds), and tell our hero the whole path. Output a line contains "FINISH" after each test case. If there are more than one path, any one is OK in this problem. More details in the Sample Output.
 

Sample Input
 
   
5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX. 5 6 .XX.1. ..X.2. 2...X. ...XX. XXXXX1 5 6 .XX... ..XX1. 2...X. ...XX. XXXXX.
 

Sample Output
 
   
It takes 13 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) FINISH It takes 14 seconds to reach the target position, let me show you the way. 1s:(0,0)->(1,0) 2s:(1,0)->(1,1) 3s:(1,1)->(2,1) 4s:(2,1)->(2,2) 5s:(2,2)->(2,3) 6s:(2,3)->(1,3) 7s:(1,3)->(1,4) 8s:FIGHT AT (1,4) 9s:FIGHT AT (1,4) 10s:(1,4)->(1,5) 11s:(1,5)->(2,5) 12s:(2,5)->(3,5) 13s:(3,5)->(4,5) 14s:FIGHT AT (4,5) FINISH God please help our poor hero. FINISH


题目说要找最短的路,遇到怪兽还要花时间打怪兽,选用的就是BFS了,根据队列先进先出的特点,达到目标点即是最短的路径。所以在遇到怪兽的时候,我们可以模拟打怪兽,将此点重新入队,这样的操作,当到达顶点的时候,也是最短的路径。而如何得知它的路径呢?我们可以在新节点入队的时候,将上一个节点存起来,那么在终点的时候,就可以回溯找到原来的路径了。下面的代码就是BFS + 队列实现AC。

import java.util.*;

public class Main {
    private static class Node {
        int x;//x坐标
        int y;//y坐标
        int step;//当钱步数
        Node node;//记录上一个节点到此节点
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int n = sc.nextInt();//行
            int m = sc.nextInt();//列
            String temp = sc.nextLine();//读取隐藏的换行符
            char[][] map = new char[n][m];//地图
            int[][] flag = new int[n][m];//标记
            //画地图
            for (int i = 0; i < n; i++) {
                String data = sc.nextLine();
                for (int j = 0; j < m; j++) {
                    map[i][j] = data.charAt(j);
                }
            }

            //起点
            Node start = new Node();
            start.x = 0;
            start.y = 0;
            start.step = 0;
            Queue queue = new LinkedList<>();
            //把起点入队
            queue.offer(start);
            while (!queue.isEmpty()) {
                //拿队头元素
                Node node = queue.peek();
                //如果是终点
                if (node.x == n - 1 && node.y == m - 1) {
                    while (map[node.x][node.y] >= '1' && map[node.x][node.y] <= '9') {
                        Node location = new Node();
                        location.x = node.x;
                        location.y = node.y;
                        location.step = node.step;
                        location.node = node.node;
                        node.step++;
                        node.node = location;
                        //怪物的hp减一
                        map[node.x][node.y]--;
                    }
                    break;//结束
                }//如果不是终点
                else {
                    //出队
                    node = queue.poll();
                    //标记走过
                    flag[node.x][node.y] = 1;
                    //将周围符合条件的入队
                    int x = node.x;
                    int y = node.y;
                    int step = node.step;
                    //如果此时的位置有怪物,原地入队
                    if (!(map[x][y] >= '1' && map[x][y] <= '9')) {
                        //上)
                        Node up = null;
                        if (x - 1 >= 0 && map[x - 1][y] != 'X' && flag[x - 1][y] != 1) {
                            up = new Node();
                            up.x = x - 1;
                            up.y = y;
                            up.step = step + 1;//当前步数加1
                            up.node = node;
                            flag[x-1][y] = 1;
                            queue.offer(up);
                        }
                        //下
                        Node down = null;
                        if (x + 1 < n && map[x + 1][y] != 'X' && flag[x + 1][y] != 1) {
                            down = new Node();
                            down.x = x + 1;
                            down.y = y;
                            down.step = step + 1;
                            down.node = node;
                            flag[x+1][y] = 1;
                            queue.offer(down);
                        }//左
                        Node left = null;
                        if (y - 1 >= 0 && map[x][y - 1] != 'X' && flag[x][y - 1] != 1) {
                            left = new Node();
                            left.x = x;
                            left.y = y - 1;
                            left.step = step + 1;
                            left.node = node;
                            flag[x][y-1] = 1;
                            queue.offer(left);
                        }
                        //右
                        Node right = null;
                        if (y + 1 < m && map[x][y + 1] != 'X' && flag[x][y + 1] != 1) {
                            right = new Node();
                            right.x = x;
                            right.y = y + 1;
                            right.step = step + 1;
                            right.node = node;
                            flag[x][y+1] = 1;
                            queue.offer(right);
                        }
                    } else {
                        {
                            Node location = new Node();
                            location.x = x;
                            location.y = y;
                            location.step = step + 1;
                            location.node = node;
                            //怪物的hp减一
                            map[x][y]--;
                            queue.offer(location);
                        }
                    }
                    node = null;
                    start = null;
                }
            }

            String finish = "FINISH";
            if (!queue.isEmpty()) {
                StringBuffer sb = new StringBuffer("It takes ");
                sb.append(queue.peek().step);
                sb.append(" seconds to reach the target position, let me show you the way.");
                System.out.println(sb.toString());
                pf(queue.peek());
                System.out.println(finish);
            } else {
                System.out.println("God please help our poor hero.");
                System.out.println(finish);
            }
            queue.clear();
            queue = null;
        }
    }

    public static void pf(Node node) {
        if (node.x == 0 && node.y == 0)
            return;
        pf(node.node);
        StringBuffer s = new StringBuffer();
        if (node.x == node.node.x && node.y == node.node.y)
            s.append(node.step).append("s:FIGHT AT (").append(node.x).append(",").append(node.y).append(")");
        else
            s.append(node.step).append("s:(").append(node.node.x).append(",").append(node.node.y).append(")->(")
                    .append(node.x).append(",").append(node.y).append(")");
        System.out.println(s);
    }
}


看到别人的博客后,得知优先队列可以实现,也用优先队列实现了一次,下面是AC代码。

import java.util.*;

public class Main {
    private static class Node {
        int x;//x坐标
        int y;//y坐标
        int step;//当钱步数
        Node node;//记录上一个节点到此节点
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int n = sc.nextInt();//行
            int m = sc.nextInt();//列
            String temp = sc.nextLine();//读取隐藏的换行符
            char[][] map = new char[n][m];//地图
            int[][] flag = new int[n][m];//标记
            int[] mx = {0, 0, 1, -1};
            int[] my = {1, -1, 0, 0};
            //画地图
            for (int i = 0; i < n; i++) {
                String data = sc.nextLine();
                for (int j = 0; j < m; j++) {
                    map[i][j] = data.charAt(j);
                }
            }
            //起点
            Node start = new Node();
            start.x = 0;
            start.y = 0;
            start.step = 0;
            Comparator comparator = new Comparator() {
                public int compare(Node o1, Node o2) {
                    return o1.step - o2.step;
                }
            };
            Queue queue = new PriorityQueue<>(comparator);
            //把起点入队
            queue.offer(start);

            Node res = null;
            while (!queue.isEmpty()) {
                //出队
                Node node = queue.poll();
                int x = node.x;
                int y = node.y;
                int step = node.step;
                flag[x][y] = 1;
                //如果到了终点
                if (x == n - 1 && y == m - 1) {
                    res = node;
                    break;
                }
                //bfs
                for (int i = 0; i < 4; i++) {
                    int x1 = x + mx[i];
                    int y1 = y + my[i];
                    //判断入队的条件
                    if (x1 >= 0 && x1 < n && y1 >= 0 && y1 < m && map[x1][y1] != 'X' && flag[x1][y1] != 1) {
                        char c = map[x1][y1];
                        Node tempNode = new Node();
                        tempNode.x = x1;
                        tempNode.y = y1;
                        tempNode.node = node;
                        flag[x1][y1] = 1;
                        if (c == '.')
                            tempNode.step = step + 1;
                        else
                            tempNode.step = step + 1 + c - '0';//基本步数再加打怪物的时间
                        queue.offer(tempNode);
                    }
                }
            }
            if (res == null) {
                System.out.println("God please help our poor hero.");
                System.out.println("FINISH");
            } else {
                System.out.println("It takes "+res.step+" seconds to reach the target position, let me show you the way.");
                pf(res);
                System.out.println("FINISH");
            }
        }
    }

    public static void pf(Node node) {
        if (node.x == 0 && node.y == 0)
            return;
        pf(node.node);
        int value = node.step - node.node.step;
        StringBuffer s = new StringBuffer();

        s.append(node.node.step + 1).append("s:(").append(node.node.x).append(",").append(node.node.y).append(")->(")
                .append(node.x).append(",").append(node.y).append(")\r\n");
        for (int i = 0; i < value - 1; i++) {
            s.append(node.node.step+2+i).append("s:FIGHT AT (").append(node.x).append(",").append(node.y).append(")\r\n");
        }

        System.out.print(s);
    }
}


你可能感兴趣的:(杭电1026_ Ignatius and the Princess I (BFS+模拟 或者 BFS+优先队列)——java)