鱼C论坛

 找回密码
 立即注册
查看: 1227|回复: 2

掌握图的邻接表表示法,实现Graph类

[复制链接]
发表于 2023-11-7 22:45:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1、实现 Graph类,并完成以下操作,写出完整代码:
(1)通过键盘输入数据创建图:
设图的顶点为:A B C D E。图的边为:<A, B,5>, <B,A,6>, <B,C,7>, <B,E,7>, <C,B,11>, <C,D,20>, <D,A,2>,<E,D,8>。
(2)通过从文件中读取数据创建图:
设图的顶点为:A B C D E。图的边为:<A, B,5>, <B,A,6>, <B,C,7>, <B,E,7>, <C,B,11>, <C,D,20>, <D,A,2>,<E,D,8>。先用记事本生成文件名为Graph1.txt的文本文件用来存储图的数据,从该文件中读取数据创建图,再把这个图的数据输出到文件Graph1_out.txt中。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-7 22:45:35 | 显示全部楼层
下面是实现 Graph 类的代码:
class Graph:
    def __init__(self):
        self.adjacency_list = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency_list:
            self.adjacency_list[vertex] = []

    def add_edge(self, start_vertex, end_vertex, weight):
        if start_vertex in self.adjacency_list and end_vertex in self.adjacency_list:
            self.adjacency_list[start_vertex].append((end_vertex, weight))
        else:
            raise ValueError("顶点不存在")

    def create_graph_from_input(self):
        vertices = input("请输入图的顶点,以空格分隔:").split()
        for vertex in vertices:
            self.add_vertex(vertex)

        edges = input("请输入图的边,格式为<起始顶点, 终止顶点, 权重>,以空格分隔:").split()
        for edge in edges:
            start_vertex, end_vertex, weight = edge[1:-1].split(',')
            self.add_edge(start_vertex, end_vertex, int(weight))

    def create_graph_from_file(self, filename):
        with open(filename, 'r') as file:
            lines = file.readlines()
            for line in lines:
                start_vertex, end_vertex, weight = line.strip().split(',')
                self.add_vertex(start_vertex)
                self.add_vertex(end_vertex)
                self.add_edge(start_vertex, end_vertex, int(weight))

    def print_graph(self):
        for vertex in self.adjacency_list:
            print(f"顶点 {vertex} 的邻接顶点及对应权重:")
            for neighbor, weight in self.adjacency_list[vertex]:
                print(f"{neighbor},权重:{weight}")

    def write_graph_to_file(self, filename):
        with open(filename, 'w') as file:
            for vertex in self.adjacency_list:
                for neighbor, weight in self.adjacency_list[vertex]:
                    file.write(f"<{vertex}, {neighbor}, {weight}>\n")

你可以使用以下代码来测试 Graph 类的功能:
graph = Graph()

# 通过键盘输入数据创建图
graph.create_graph_from_input()
graph.print_graph()

# 通过从文件中读取数据创建图
graph.create_graph_from_file("Graph1.txt")
graph.print_graph()

# 把图的数据输出到文件Graph1_out.txt中
graph.write_graph_to_file("Graph1_out.txt")

请确保在运行代码之前,已经创建了  Graph1.txt  文件,并将图的数据写入该文件中。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-11-7 22:46:23 | 显示全部楼层
实现Graph类并进行操作

以下是C++中实现Graph类以及通过键盘输入数据和从文件中读取数据创建图并将数据输出到文件的完整代码:
#include <iostream>#include <fstream>#include <vector>#include <unordered_map>// 边的结构体struct Edge {    char start;    char end;    int weight;};class Graph {private:    std::unordered_map<char, std::vector<std::pair<char, int>>> adjacencyList;public:    // 添加边    void addEdge(char start, char end, int weight) {        adjacencyList[start].push_back(std::make_pair(end, weight));    }    // 通过键盘输入数据创建图    void createGraphFromInput() {        char vertices[] = {'A', 'B', 'C', 'D', 'E'};        std::vector<Edge> edges = {{'A', 'B', 5}, {'B', 'A', 6}, {'B', 'C', 7}, {'B', 'E', 7},                                   {'C', 'B', 11}, {'C', 'D', 20}, {'D', 'A', 2}, {'E', 'D', 8}};        for (auto edge : edges) {            addEdge(edge.start, edge.end, edge.weight);        }    }    // 从文件中读取数据创建图    void createGraphFromFile(const std::string& filename) {        std::ifstream file(filename);        char start, end;        int weight;        while (file >> start >> end >> weight) {            addEdge(start, end, weight);        }        file.close();    }    // 将图的数据输出到文件    void outputGraphToFile(const std::string& filename) {        std::ofstream outFile(filename);        for (const auto& pair : adjacencyList) {            char start = pair.first;            for (const auto& edge : pair.second) {                char end = edge.first;                int weight = edge.second;                outFile << "<" << start << ", " << end << ", " << weight << ">\n";            }        }        outFile.close();    }};int main() {    Graph graph;    // 通过键盘输入数据创建图    graph.createGraphFromInput();    // 输出到文件Graph1_out.txt    graph.outputGraphToFile("Graph1_out.txt");    // 从文件中读取数据创建图    Graph graphFromFile;    graphFromFile.createGraphFromFile("Graph1.txt");    // 输出到文件Graph1_out.txt    graphFromFile.outputGraphToFile("Graph1_out.txt");    return 0;}
在上面的代码中,我们首先定义了一个Graph类,它使用邻接表来表示图。通过addEdge函数,我们可以添加边。createGraphFromInput函数用于通过键盘输入数据创建图,createGraphFromFile函数用于从文件中读取数据创建图,并且outputGraphToFile函数用于将图的数据输出到文件。

希望这个代码能够满足你的需求。如果有任何问题,欢迎随时提问。

球一个最佳答案谢谢啦!这对我非常重要!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-7 03:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表