广度优先搜索与最短路径问题

------------马的最短路径

题目描述:
一匹马在一个8*8的棋盘上走着,它的每一步恰好走成一个日字,也就是在x、y两个方向上,如果在一个方向走一步,另一个方向就走两步。假设棋盘的下标左下角是(1,1),右上角是(8,8)。给你马的最初位置(a,b)各最终位置(an,bn),请你编程求出马从最初位置到最终位置所走的最少步数。
Input
先输入一个正整数T表示有T种情况,每一种情况一行,由四个正整数组成,分别表示a、b、an、bn。
Ouput
每种情况先输出“Case :id”,id是从1开始的序号,然后输出马走的最小步数。
输入:

2
1 1 2 3
5 2 5 4

输出:

Case 1:1
Case 2:2

代码展示:

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

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
            int[][] array = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
            int n = in.nextInt();
            for(int i = 1; i <= n; i++){
                int[][] vis = new int[9][9];
                Queue<Horse> queue = new LinkedList<Horse>();
                int x = in.nextInt();
                int y = in.nextInt();
                int endX = in.nextInt();
                int endY = in.nextInt();
                queue.add(new Horse(x,y,0));
                while (!queue.isEmpty()){
                    Horse h = queue.poll();
                    if(h.getX()==endX && h.getY()==endY){
                        System.out.println("Case "+i+":"+h.getStep());
                        break;
                    }else{
                        for(int j = 0; j < 8; j++){
                            Horse hh = new Horse(h.getX()+array[j][0],h.getY()+array[j][1],h.getStep()+1);
                            if(hh.getX()>=1&&hh.getX()<=8&&hh.getY()>=1&&hh.getY()<=8&&vis[hh.getX()][hh.getY()]!=1){
                                queue.add(hh);
                            }
                        }
                        vis[h.getX()][h.getY()] = 1;
                    }
                }
            }
        }
}
class Horse{
    private int x,y,step;

    public Horse(int x, int y, int step) {
        this.x = x;
        this.y = y;
        this.step = step;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }
}

注:
因为广度优先遍历与层次遍历类似,按层搜索的,先第一层、第二层…… 第n层。因为是一层一层地搜索,第一层没有,就在第二层找,第二层没有,就在第三层找…… 若在第k层找到了,说明在[0, k-1]层中都没有找到目标。所以k一定是最短的层数,即最短路。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值