第一行一个数表示数据组数
每组数据第一行两个数。含义见题意。
接下来m行每行两个数表示
到
之间有一条边
每组数据一行如果能回到公司输出“POSSIBLE”,不能输出"IMPOSSIBLE"。
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"); } } } }