HDU1026—Ignatius and the Princess I

来源:互联网 发布:莫斯科奥运会知乎 编辑:程序博客网 时间:2024/06/05 19:35

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026

 

package Search;/* * 题目意思:迷宫搜索题,大概意思是说从0,0出发走到最后 * 规则:.表示可以走的。X表示是陷阱,不能走的,数字表示怪物,每次跟怪物决斗都要花费n秒。 * 求最少的时间花费并且打印每一步 *  * 思路: *  * 一般来说,广搜常用于找单一的最短路线,或者是规模小的路径搜索,它的特点是"搜到就是最优解",  * 而深搜用于找多个解或者是"步数已知(好比3步就必需达到前提)"的标题, * 它的空间效率高,然则找到的不必定是最优解,必需记实并完成全数搜索, * 故一般情况下,深搜需要很是高效的剪枝(优化). *  * 此题用bfs *  * */import java.util.*;public class HDU1206_2 {static class Node implements Comparable<Node>{//到达(x,y)的时间sint x,y,s;public Node(int x,int y,int s){this.x = x;this.y = y;this.s = s;}@Overridepublic int compareTo(Node o) {return s - o.s;}}//n*m的迷宫mapstatic int n,m;static char[][]map;//path[x][y]表示到达x,y的前一个节点static Node[][]path;static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};//方向public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){n = sc.nextInt();m = sc.nextInt();map = new char[n][m];String str;for(int i = 0;i<n;i++){str = sc.next();for(int j = 0;j<m;j++){map[i][j] = str.charAt(j);}}if(!bfs()){System.out.println("God please help our poor hero.");}else printPath();System.out.println("FINISH");}}//广搜private static boolean bfs() {boolean success = false;//标志是否找到最后Queue<Node> que = new PriorityQueue<Node>();path = new Node[n+1][m+1];//visited[x][y]表示x,y位置是否到达过boolean[][] visited = new boolean[n][m]; //迷宫入口Node node = new Node(0,0,0);if(Character.isDigit(map[0][0]))node.s = map[0][0] - '0';//如果入口时怪时que.add(node);visited[0][0] = true;path[0][0] = node;while(!success && !que.isEmpty()){node = que.poll();//到达n-1,m-1表示到达出口if(node.x==n-1 && node.y == m-1){success = true;path[n][m] = node;break;}//向四个方向搜索for(int i = 0;i<4;i++){int x = node.x + dir[i][0];int y = node.y + dir[i][1];int s = node.s;//超出边界、已经访问、已經走過、陷阱if(x < 0||x>=n||y<0||y>=m||visited[x][y]||map[x][y]=='X')continue;visited[x][y] = true;if(map[x][y]=='.') s = s+1;else s = s+1+map[x][y]-'0';path[x][y] = node;//记录x,y的前一个位置que.add(new Node(x,y,s));}}return success;}//打印路径private static void printPath() {Node node = path[n][m];System.out.println("It takes "+node.s+" seconds to reach the target position, let me show you the way.");List<String> list = new ArrayList<String>();Node pre = node;//从出口到入口反向输出路径while(!(node.x == 0) || !(node.y==0)){pre = path[node.x][node.y];if(map[node.x][node.y] == '.')list.add(node.s + "s:("+pre.x+","+pre.y+")->(" + node.x+","+node.y+")");else {int sec = map[node.x][node.y] - '0';for(int i = 0;i<sec;i++)list.add((node.s-i) + "s:FIGHT AT ("+node.x+","+node.y+")");list.add((node.s-sec) + "s:("+pre.x+","+pre.y+")->(" + node.x+","+node.y+")");}node = pre;}if(pre.s>0){node = path[0][0];if(Character.isDigit(map[0][0])){int sec = map[node.x][node.y] - '0';for(int i = 0;i<sec;i++)list.add((node.s-i) + "s:FIGHT AT ("+node.x+","+node.y+")");}else{list.add(node.s + "s:("+pre.x+","+pre.y+")->(" + node.x+","+node.y+")");}}for(int i = list.size()-1;i>=0;i--){System.out.println(list.get(i));}}}


 

 

原创粉丝点击