You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从边文件生成图:Java代码实现与输出格式调整需求

我帮你调整了代码,完全贴合你的需求——从指定文件读取边数据,然后按0 -> 1 -> 3;1 -> 2 -> 3;2 -> 3的格式输出邻接表。先看修正后的完整代码:

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Graph {
    // 构建邻接表,默认处理为有向边(符合你的预期输出)
    public static void addEdge(Map<Integer, List<Integer>> adj, int u, int v) {
        // 自动创建顶点对应的邻接列表,避免空指针
        adj.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
        // 如果需要无向图,取消下面这行注释即可
        // adj.computeIfAbsent(v, k -> new ArrayList<>()).add(u);
    }

    public static void read(String filename) {
        Map<Integer, List<Integer>> adj = new HashMap<>();
        File input = new File(filename); // 使用传入的文件名,不再硬编码
        // try-with-resources自动关闭扫描器,不用手动close
        try (Scanner reader = new Scanner(input)) {
            while (reader.hasNextLine()) {
                // 按空格分割每行里的多条边
                String[] edges = reader.nextLine().split(" ");
                for (String edge : edges) {
                    // 按逗号分割顶点(你的边文件里是0,1这种格式,没有空格)
                    String[] nums = edge.split(",");
                    int u = Integer.parseInt(nums[0]);
                    int v = Integer.parseInt(nums[1]);
                    addEdge(adj, u, v);
                }
            }
            printGraph(adj);
        } catch (IOException e) {
            throw new RuntimeException("读取文件时出错啦", e);
        }
    }

    static void printGraph(Map<Integer, List<Integer>> adj) {
        // 把顶点按升序排序,保证输出顺序是0、1、2的顺序
        List<Integer> sortedVertices = new ArrayList<>(adj.keySet());
        Collections.sort(sortedVertices);

        StringBuilder sb = new StringBuilder();
        for (int u : sortedVertices) {
            List<Integer> neighbors = adj.get(u);
            if (neighbors.isEmpty()) continue; // 没有出边的顶点不输出
            sb.append(u);
            for (int v : neighbors) {
                sb.append(" -> ").append(v);
            }
            sb.append(";"); // 用中文分号分隔每个顶点的邻接表
        }
        // 移除最后多余的分号
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 1);
        }
        System.out.println(sb.toString());
    }

    // 测试用主方法,替换成你的实际文件名即可
    public static void main(String[] args) {
        read("edges.txt");
    }
}

主要修改点说明:

  • 理顺类结构:把原来分散的Graph1、Graph2和不存在的AddEdge合并成一个Graph类,代码逻辑更集中,不容易出错。
  • 修复文件读取问题:
    • 原来硬写死的"filename"改成了方法参数,你传入不同的文件名就能处理不同的边文件。
    • 你的边文件是用空格分隔每条边(比如0,1 0,3),所以先按空格拆分所有边,再对每条边按逗号拆分顶点(原代码用了", "带空格的分割符,和你的文件格式不匹配)。
  • 调整邻接表结构:用List替代Set,保证邻接点的顺序;同时默认按有向边处理(如果是无向图,只需要取消addEdge里反向添加的注释)。
  • 匹配预期输出格式:
    • 对顶点升序排序,确保输出顺序符合你的预期。
    • 用StringBuilder拼接内容,输出格式完全是你想要的0 -> 1 -> 3;1 -> 2 -> 3;2 -> 3,还自动跳过了没有出边的顶点(比如例子里的3)。

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:52:48