龚秋志


私信TA

用户名:uq_48078956563

访问量:48602

签 名:

等  级
排  名 34
经  验 13274
参赛次数 30
文章发表 64
年  龄 19
在职情况 学生
学  校 湖北生物科技职业学院
专  业 计算机应用

  自我简介:

解题思路:以为很难,没想到就是走迷宫的原题 就是方向变了

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

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] direction = { { -1, -2 }, { -2, -1 }, { -2, 1 }, { -1, 2 },
                { 1, -2 }, { 2, -1 }, { 2, 1 }, { 1, 2 } };
        for (int i = 0; i < n; i++) {
            int L = sc.nextInt();
            int[][] arr = new int[L + 1][L + 1];
            int startx = sc.nextInt();
            int starty = sc.nextInt();
            int endx = sc.nextInt();
            int endy = sc.nextInt();
            if (startx == endx && endy == starty) {
                System.out.println(0);
                continue;
            }
            int k = 0;
            boolean iRet = true;
            LinkedList<nnn> queue = new LinkedList<nnn>();
            queue.add(new nnn(startx, starty, 0));
            arr[startx][starty] = 1;
            while (!queue.isEmpty()) {
                nnn d = queue.poll();
                k = d.step;
                if (d.x == endx && d.y == endy) {
                    System.out.println(d.step);
                    iRet = false;
                    break;
                }
                for (int j = 0; j < direction.length; j++) {
                    int x = d.x + direction[j][0];
                    int y = d.y + direction[j][1];
                    if (x >= 0 && y >= 0 && x < L && y < L && arr[x][y] == 0) {
                        arr[x][y] = 1;
                        queue.addLast(new nnn(x, y, d.step + 1));
                    }
                }
            }
            if(iRet)System.out.println(k);
        }
    }

}

class nnn {
    public int x;
    public int y;
    public int step;

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


 

0.0分

4 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

太猛了。
2021-01-07 16:03:33
墙都不扶就服你
2020-10-14 11:16:31
  • «
  • 1
  • »