算法 BISHI100 【模板】二分图结构Ⅰ-A ‖ 染色判定:DFS 思路 求解代码 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 57 58 59 60 61 62 63 64 65 66 67 public static void main(String[] args) throws IOException { // 使用 BufferedReader 和 PrintWriter 提升大规模数据下的 I/O 效率 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // 读取输入的第一行,包含两个整数n和m,分别表示顶点数和边数 String[] strA = br.readLine().trim().split("\\s+"); int n = Integer.parseInt(strA[0]); // 顶点数 int m = Integer.parseInt(strA[1]); // 边数 // 创建邻接表表示的无向图 List<Integer>[] adj = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) { adj[i] = new ArrayList<>(); } // 读取所有边的信息,构建无向图 for (int i = 0; i < m; i++) { String[] edge = br.readLine().trim().split("\\s+"); int u = Integer.parseInt(edge[0]); // 边的一个端点 int v = Integer.parseInt(edge[1]); // 边的另一个端点 adj[u].add(v); // 添加边到邻接表 adj[v].add(u); // 无向图,双向添加 } // color数组用于记录每个顶点的颜色,0表示未染色,1和2表示两种不同的颜色 int[] color = new int[n + 1]; boolean flag = true; // 标记是否为二分图 // 使用队列实现BFS Queue<Integer> queue = new LinkedList<>(); // 从顶点1开始染色,并将其加入队列 queue.add(1); color[1] = 1; // BFS遍历图 while (!queue.isEmpty()) { int cur = queue.poll(); // 取出队首顶点 // 遍历当前顶点的所有邻接顶点 for (int neighbor : adj[cur]) { // 如果邻接顶点未被染色 if (color[neighbor] == 0) { // 将邻接顶点染成与当前顶点不同的颜色 color[neighbor] = 3 - color[cur]; queue.add(neighbor); // 将邻接顶点加入队列 } else if (color[neighbor] == color[cur]) { // 如果邻接顶点与当前顶点颜色相同,则不是二分图 flag = false; break; } } } // 输出结果:如果是二分图输出"YES",否则输出"NO" out.println(flag ? "YES" : "NO"); // 刷新输出缓冲区,确保所有输出都被写入 out.flush(); // 关闭输出流 out.close(); // 关闭输入流 br.close(); }