ccf历年第四题java解答之-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));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_23934649/article/details/82141936