HDU1026

来源:互联网 发布:java ioc容器 编辑:程序博客网 时间:2024/05/22 05:15

:n*m迷宫,求从(0,0)到(n-1,m-1)的最少时间。'X'是墙,'.'是空地,'1'-'9'表示有怪物,消灭之需要数字对应的时间。


import java.io.BufferedInputStream;import java.io.PrintWriter;import java.util.PriorityQueue;import java.util.Queue;import java.util.Scanner;public class Main {public static void main(String[] args) { new HDU1026().Solve() ; }}class HDU1026{Scanner in = new Scanner(new BufferedInputStream(System.in)) ;PrintWriter out = new PrintWriter(System.out) ;void Solve(){while(in.hasNext()){   n = in.nextInt() ;    m = in.nextInt() ;      for(int i = 0 ; i < n ; i++)  g[i] =  in.next().toCharArray() ;               Point end = bfs() ;      if(end == null){      out.println("God please help our poor hero.") ;       }      else{       out.println("It takes " + end.step + " seconds to reach the target position, let me show you the way.") ;          dfs(end, end.step) ;      }   out.println("FINISH") ;}out.flush() ;}int n , m ;final int N = 108 ;final int inf = 1000000000 ;char[][] g = new char[N][N] ;int[][] dir = new int[][]{ {-1 , 0} , {0 , -1} , {1 , 0} , {0 , 1} } ;int[][] minStep = new int[N][N] ;boolean can(int x , int y){return 0 <= x && x < n && 0 <= y && y < m ; }Point bfs(){if(g[0][0] == 'X') return null ;for(int i = 0 ; i < n ; i++){for(int j = 0 ; j < m ; j++) minStep[i][j] = inf ;}Queue<Point> q = new PriorityQueue<Point>() ;        q.add(new Point(0 ,  0 ,  minStep[0][0] = getStep(g[0][0]) - 1  , null) ) ;while(! q.isEmpty()){Point u = q.poll() ;if(u.x == n-1 && u.y == m-1) return u ;for(int i = 0 ; i < 4 ; i++){int x = u.x + dir[i][0] ;int y = u.y + dir[i][1] ;if(can(x, y) && g[x][y] != 'X'){if(u.step + getStep(g[x][y]) < minStep[x][y]){    q.add(new Point(x, y, u.step + getStep(g[x][y]) , u) ) ;    minStep[x][y] = u.step + getStep(g[x][y]) ; }}}}return null ;}int  getStep(char c){ if(c == '.') return 1 ; else return c - '0' + 1 ; }void dfs(Point u , int endStep){ if(u.father == null) return ;  if(g[u.x][u.y] == '.'){  dfs(u.father ,  endStep - 1) ;  out.println(endStep + "s:" + u.father + "->" + u)  ; } else{ dfs(u.father ,  endStep - getStep(g[u.x][u.y]) ) ; out.println(endStep - getStep(g[u.x][u.y] ) + 1 + "s:" + u.father + "->" + u)  ; for(int i = endStep - getStep(g[u.x][u.y]) + 2 ; i <= endStep  ; i++) out.println(i + "s:FIGHT AT "  + u)  ; }}}class Point implements Comparable<Point>{int x ;int y ;int step ;Point father ;Point(int x , int y , int step , Point father) {this.x = x ;this.y = y ;this.step = step ;this.father = father ;}@Overridepublic String toString() {return "(" + x + "," + y + ")" ;}@Overridepublic int compareTo(Point other) {return Integer.compare(step, other.step) ;} }


0 0