您的位置:首页 > 其它

HDU1026

2016-06-03 21:20 309 查看
: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

;
int[][] dir = new int[][]{ {-1 , 0} , {0 , -1} , {1 , 0} , {0 , 1} } ;
int[][] minStep = new int

;
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 ;
}

@Override
public String toString() {
return "(" + x + "," + y + ")" ;
}

@Override
public int compareTo(Point other) {
return Integer.compare(step, other.step) ;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: