poj 2243 Knight Moves

本文介绍了一种使用Java实现的宽度优先搜索(BFS)算法来解决骑士走法问题的方法。通过定义方向数组并利用LinkedList作为队列进行节点扩展,实现了从源位置到目标位置的最短步数计算。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值