您的位置:首页 > 其它

poj 2243 Knight Moves

2010-07-24 19:24 239 查看
http://162.105.81.212/JudgeOnline/problem?id=2243

用Java解题, 解得我蛋疼-_-||

很多东西都忘记了....

写一个bfs,搞了半天,还不知道错那里了。

后来才发现,原来是因为每次加入队列的都是同一个对象导致的,囧

题目很简单,如果不知道怎么写方向数组,可参考poj19115(有图),这两题很相似。

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
static class Point implements Comparable<Point> {
int x, y, step;
public int compareTo(Point p) {
if(x == p.x && y == p.y)
return 1;
else
return 0;
}
}
static Point src = new Point(), des = new Point();
static int dirx[] = {1,  2,  2, 1, -1, -2, -2, -1};
static int diry[] = {-2, -1, 1, 2, 2,   1, -1, -2};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a, b;
while(in.hasNext()) {
a = in.next();
b = in.next();
src.x = a.charAt(0) - 'a' + 1;
src.y = a.charAt(1) - '0';
src.step = 0;
des.x = b.charAt(0) - 'a' + 1;
des.y = b.charAt(1) - '0';
System.out.println("To get from " + a + " to " + b + " takes " + bfs() + " knight moves.");
}
}

public static int bfs() {
Point tmp = new Point();
LinkedList<Point> Que = new LinkedList<Point>();
//加入一个src
Que.addLast(src);
while(!Que.isEmpty()) {
tmp = Que.getFirst();
Que.removeFirst();
if(tmp.compareTo(des) == 1)
return tmp.step;
for(int j=0; j<8; j++) {
//每次這裡都要new, 因為隊列或數組等都是加入的對象, 如果沒有new, 這裡就會改變原來已經加入隊列的cur的值.
Point cur = new Point();
cur.x = tmp.x + dirx[j];
cur.y = tmp.y + diry[j];
cur.step = tmp.step + 1;
if(check(cur)) {
Que.addLast(cur);
}
}
}
return -1;
}

public static boolean check(Point p) {
if(p.x >=1 && p.y >=1 && p.x <= 8 && p.y <= 8)
return true;
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: