【POJ1915】 Knight Moves骑士移动(宽度优先搜索Java版)

POJ1915题目详情见官网:http://poj.org/problem?id=1915
思维导图攻破算法难题
算法思路视频讲解请点击——> b站poj 1915算法思路讲解
手敲代码讲解视频请点击——> b站poj 1915代码讲解

更多精彩视频(Letecode刷题、互联网大厂笔试刷题)请在bilibili搜索鲁班代师,然后搜索题号就可以,关注不走丢,感谢。
欢迎批评指正、探讨!

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

public class Main
{
    public static int[] dx = {-2, -1, 1, 2, 2, 1, -1, -2};
    public static int[] dy = {1, 2, 2, 1, -1, -2, -2, -1};
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        while(--n >= 0)
        {
                int l = sc.nextInt();
                int beginx = sc.nextInt();
                int beginy = sc.nextInt();
                int endx = sc.nextInt();
                int endy = sc.nextInt();
               ans = BFS_move(beginx, beginy, endx, endy, l);
               System.out.println(ans);
        }
    }
    public static int BFS_move(int beginx, int beginy, int endx, int endy, int l)
    {
        int[][] mark = new int[l][l];
        for(int i = 0; i < l; i++)
        {
            for (int j = 0; j < l; j++)
            {
                mark[i][j] = 0;
            }
        }
        Queue<Location> Q = new LinkedList<Location>();
        Location lc = new Location(beginx, beginy, 0);
        Q.add(lc);
        mark[beginx][beginy] = 1;
        while (!Q.isEmpty())
        {
            lc = Q.poll();
            if(lc.x == endx && lc.y == endy)
            {
                return lc.distance;
            }
            for(int i = 0; i < 8; i++)
            {
                int newx = lc.x + dx[i];
                int newy = lc.y + dy[i];
                if( newx >= 0 && newx < l && newy >= 0 && newy < l && mark[newx][newy] == 0)
                {
                    Q.add(new Location(newx, newy, lc.distance + 1));
                    mark[newx][newy] = 1;
                }
            }
        }
        return -1;
    }
}
class Location
{
    int x;
    int y;
    int distance;
    public Location(int x, int y, int distance)
    {
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}

发布了3 篇原创文章 · 获赞 0 · 访问量 107

猜你喜欢

转载自blog.csdn.net/qq_21998503/article/details/105651996
今日推荐