首页 > 试题广场 >

返回公司

[编程题]返回公司
  • 热度指数:898 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
度度熊迷路了他想返回他的公司,他现在在号点,他的公司在号点。度度熊所在的城市由个点和条边组成,因为度度熊走了一天了很累,他还有走两条边的体力,度度熊想知道他能否回到公司呢?

输入描述:
第一行一个数表示数据组数
每组数据第一行两个数。含义见题意。
接下来m行每行两个数a_i,b_i表示a_ib_i之间有一条边


输出描述:
每组数据一行如果能回到公司输出“POSSIBLE”,不能输出"IMPOSSIBLE"。
示例1

输入

1
4 3
1 2
2 3
3 4

输出

IMPOSSIBLE
// 标准bfs

import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        // T组数据
        for (int i = 0; i < T; i++) {
            // n个点,m条边
            int n = sc.nextInt();
            int m = sc.nextInt();

            HashSet<Integer> visited = new HashSet<>();
            Map<Integer, List<Integer>> neighbors = new HashMap<>();
            for (int j = 0; j < n; j++) {
                neighbors.put(j + 1, new ArrayList<>());
            }

            for (int j = 0; j < m; j++) {
                int point1 = sc.nextInt();
                int point2 = sc.nextInt();
                List<Integer> list1 = neighbors.get(point1);
                list1.add(point2);
                neighbors.put(point1, list1);
                List<Integer> list2 = neighbors.get(point2);
                list2.add(point1);
                neighbors.put(point2, list2);
            }

            boolean flag = false;

            int length = 0;
            Queue<Integer> queue = new LinkedList<>();
            queue.add(1);
            while (!queue.isEmpty() && !flag) {
                int size = queue.size();
                length++;
                for (int j = 0; j < size; j++) {
                    int point = queue.poll();
                    if (point == n && length == 3) {
                        flag = true;
                    }
                    visited.add(point);
                    List<Integer> nexts = neighbors.get(point);
                    for (int k = 0; k < nexts.size(); k++) {
                        int next = nexts.get(k);
                        if (!visited.contains(next)) {
                            queue.add(next);
                        }
                    }
                }
            }
            if (flag){
                System.out.println("POSSIBLE");
            }else {
                System.out.println("IMPOSSIBLE");
            }
        }
    }

}  

发表于 2022-03-07 20:14:48 回复(1)