201403-4 无线网络

使用bfs求解(耗时156ms,得分100)


import java.util.*;

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

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

}

public class Main {
    private static int n, r;
    private static Node[] nodes;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] firstLine = scanner.nextLine().split(" ");
        int num1 = Integer.parseInt(firstLine[0]);
        int num2 = Integer.parseInt(firstLine[1]);
        r = Integer.parseInt(firstLine[3]);

        n = num1 + num2;
        nodes = new Node[n];
        for (int i = 0; i < n; i++) {
            String[] line = scanner.nextLine().split(" ");
            int x = Integer.parseInt(line[0]);
            int y = Integer.parseInt(line[1]);
            nodes[i] = new Node(x, y, 0);
        }

        scanner.close();

        System.out.println(bfs());
    }

    private static int bfs() {
        Queue<Node> queue = new LinkedList<>();
        queue.add(nodes[0]);

        boolean[] visited = new boolean[n];
        visited[0] = true;

        while (!queue.isEmpty()) {

            Node front = queue.poll();

            if (front.x == nodes[1].x && front.y == nodes[1].y) {
                return front.step - 1;
            }

            for (int i = 0; i < n; i++) {
                if (visited[i])
                    continue;
                if (!inDistance(nodes[i], front))
                    continue;

                visited[i] = true;
                queue.add(new Node(nodes[i].x, nodes[i].y, front.step + 1));
            }

        }


        return 0;
    }

    private static boolean inDistance(Node n1, Node n2) {
        return r >= Math.sqrt(Math.pow(n1.x - n2.x, 2) + Math.pow(n1.y - n2.y, 2));
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值