转载自:
http://www.cnblogs.com/kdy71107216/archive/2010/08/06/1794447.html
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
boolean graph[][];
int tableTwo[][];
int path[][] = {{-1,0},{1,0},{0,1},{0,-1}};
int sx,sy,tx,ty,n,m;
PriorityQueue tableOne;
private Scanner reader = null;
public int solve(){
readInput();
init();
return aStar();
}
private boolean isAnswer(State state){
return state.x == tx && state.y == ty;
}
State step(State state, int dir){
int dirx = state.x + path[dir][0];
int diry = state.y + path[dir][1];
if(dirx >= n || dirx < 0 || diry >= m || diry < 0)
return null;
if(!graph[dirx][diry])
return null;
State newState = new State();
newState.x = dirx;
newState.y = diry;
return newState;
}
private void expand(State state){
for(int i = 0;i < path.length;i++){
State newState = step(state,i);
if(newState == null) continue;
newState.h = calc(newState);
newState.g = state.g + 1;
newState.f = newState.h + newState.g;
if(insertIntoTableTwo(newState))
insertIntoTableOne(newState);
}
}
private void insertIntoTableOne(State state){
tableOne.add(state);
}
private boolean insertIntoTableTwo(State state){
if(tableTwo[state.x][state.y] <= state.f)
return false;
tableTwo[state.x][state.y] = state.f;
return true;
}
private int aStar(){
boolean ok = false;
while(!ok && ! tableOne.isEmpty()){
State tmp = (State)tableOne.poll();
if(isAnswer(tmp)){
return tmp.f;
}else {
expand(tmp);
}
}
return -1;
}
public class StateComparator implements Comparator{
public int compare(Object arg0, Object arg1) {
State s1 = (State)arg0;
State s2 = (State)arg1;
return s1.f - s2.f;
}
}
public class State{
public int x;
public int y;
public int f;
public int g;
public int h;
};
int calc(State state){
return (int)Math.sqrt(Math.pow(state.x - tx, 2) + Math.pow(state.y - ty,2));
}
void init(){
reader = new Scanner(System.in);
n = reader.nextInt();
m = reader.nextInt();
reader.nextLine();
graph = new boolean [n][m];
tableTwo = new int [n][m];
tableOne = new PriorityQueue(100000, new StateComparator());
readInput();
for(int i = 0;i < tableTwo.length;i++){
for(int j = 0;j < tableTwo[0].length;j++){
tableTwo[i][j] = Integer.MAX_VALUE;
}
}
State newState = new State();
newState.x = sx;
newState.y = sy;
newState.g = 0;
newState.h = calc(newState);
newState.f = newState.g + newState.h;
tableOne.add(newState);
tableTwo[sx][sy] = newState.f;
}
void readInput(){
for(int i = 0;i < n;i++){
String buf = reader.nextLine();
for(int j = 0;j < m;j++){
if(buf.charAt(j) == '.'){
graph[i][j] = true;
} else if(buf.charAt(j) == '*'){
graph[i][j] = false;
} else if(buf.charAt(j) == 'S'){
graph[i][j] = true;
sx = i; sy = j;
} else if(buf.charAt(j) == 'T'){
graph[i][j] = true;
tx = i; ty = j;
}
}
}
}
public static void main(String [] args){
Main maze = new Main();
maze.init();
System.out.println(maze.aStar());
}
}