我的博客

百度笔试-度度熊迷路了

目录
  1. 输入描述
  2. 输出描述
  3. 样例
  • 解答
  • 题目描述

    度度熊迷路了他想返回他的公司,他现在在 1 号点,他的公司在 n 号点。度度熊所在的城市由 n 个点和 m 条边组成,因为度度熊走了一天了很累,他还有走两条边的体力,度度熊想知道他能否回到公司呢?

    输入描述

    第一行一个数 T 表示数据组数(1 ≤ T ≤ 10)

    每组数据第一行两个数 n,m。含义见题意。(3 ≤ n ≤ 2 × 10^5,1 ≤ m ≤ 1 × 10^5)

    接下来 m 行每行两个数 a_i,b_i 表示 a_i 到 b_i 之间有一条边

    输出描述

    每组数据输出一行如果能回到公司输出 “POSSIBLE”,不能输出 “IMPOSSIBLE”

    样例

    输入

    1
    4 3
    1 2
    2 3
    3 4

    输出

    IMPOSSIBLE

    解答

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    import java.util.*;

    public class Main {
    static private class Pair {
    Pair(int c, int d) {
    cur = c;
    depth = d;
    }
    int cur, depth;
    }

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();
    while (T-- != 0) {
    Map<Integer, ArrayList<Integer>> mp = new HashMap<>();
    int n = sc.nextInt();
    int m = sc.nextInt();
    int []x = new int[n+1];
    for (int i = 0; i < m; i++) {
    int s, e;
    s = sc.nextInt();
    e = sc.nextInt();
    if (!mp.containsKey(s)) {
    mp.put(s, new ArrayList<>());
    }
    if (!mp.containsKey(e)) {
    mp.put(e, new ArrayList<>());
    }
    mp.get(s).add(e);
    mp.get(e).add(s);
    }
    Queue<Pair> queue = new LinkedList<Pair>();
    queue.add(new Pair(1, 1));
    x[1] = 1;
    while (!queue.isEmpty()) {
    Pair p = queue.poll();
    if (p.depth < 3) {
    ArrayList<Integer> a = mp.get(p.cur);
    for (int i = 0; i < a.size(); i++) {
    if (x[a.get(i)] == 0) {
    queue.add(new Pair(a.get(i), p.depth+1));
    x[a.get(i)] = 1;
    }
    }
    }
    }
    if (x[n] == 1) {
    System.out.println("POSSIBLE");
    }
    else {
    System.out.println("IMPOSSIBLE");
    }
    }
    }
    }

    评论无需登录,可以匿名,欢迎评论!