鱼C论坛

 找回密码
 立即注册
查看: 1833|回复: 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中。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-11-7 22:45:35 | 显示全部楼层
下面是实现 Graph 类的代码:

  1. class Graph:
  2.     def __init__(self):
  3.         self.adjacency_list = {}

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

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

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

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

  20.     def create_graph_from_file(self, filename):
  21.         with open(filename, 'r') as file:
  22.             lines = file.readlines()
  23.             for line in lines:
  24.                 start_vertex, end_vertex, weight = line.strip().split(',')
  25.                 self.add_vertex(start_vertex)
  26.                 self.add_vertex(end_vertex)
  27.                 self.add_edge(start_vertex, end_vertex, int(weight))

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

  33.     def write_graph_to_file(self, filename):
  34.         with open(filename, 'w') as file:
  35.             for vertex in self.adjacency_list:
  36.                 for neighbor, weight in self.adjacency_list[vertex]:
  37.                     file.write(f"<{vertex}, {neighbor}, {weight}>\n")
复制代码


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

  1. graph = Graph()

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

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

  8. # 把图的数据输出到文件Graph1_out.txt中
  9. graph.write_graph_to_file("Graph1_out.txt")
复制代码


请确保在运行代码之前,已经创建了  Graph1.txt  文件,并将图的数据写入该文件中。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

以下是C++中实现Graph类以及通过键盘输入数据和从文件中读取数据创建图并将数据输出到文件的完整代码:
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <unordered_map>
  5. // 边的结构体
  6. struct Edge {
  7.     char start;
  8.     char end;
  9.     int weight;
  10. };
  11. class Graph {
  12. private:
  13.     std::unordered_map<char, std::vector<std::pair<char, int>>> adjacencyList;
  14. public:
  15.     // 添加边
  16.     void addEdge(char start, char end, int weight) {
  17.         adjacencyList[start].push_back(std::make_pair(end, weight));
  18.     }
  19.     // 通过键盘输入数据创建图
  20.     void createGraphFromInput() {
  21.         char vertices[] = {'A', 'B', 'C', 'D', 'E'};
  22.         std::vector<Edge> edges = {{'A', 'B', 5}, {'B', 'A', 6}, {'B', 'C', 7}, {'B', 'E', 7},
  23.                                    {'C', 'B', 11}, {'C', 'D', 20}, {'D', 'A', 2}, {'E', 'D', 8}};
  24.         for (auto edge : edges) {
  25.             addEdge(edge.start, edge.end, edge.weight);
  26.         }
  27.     }
  28.     // 从文件中读取数据创建图
  29.     void createGraphFromFile(const std::string& filename) {
  30.         std::ifstream file(filename);
  31.         char start, end;
  32.         int weight;
  33.         while (file >> start >> end >> weight) {
  34.             addEdge(start, end, weight);
  35.         }
  36.         file.close();
  37.     }
  38.     // 将图的数据输出到文件
  39.     void outputGraphToFile(const std::string& filename) {
  40.         std::ofstream outFile(filename);
  41.         for (const auto& pair : adjacencyList) {
  42.             char start = pair.first;
  43.             for (const auto& edge : pair.second) {
  44.                 char end = edge.first;
  45.                 int weight = edge.second;
  46.                 outFile << "<" << start << ", " << end << ", " << weight << ">\n";
  47.             }
  48.         }
  49.         outFile.close();
  50.     }
  51. };
  52. int main() {
  53.     Graph graph;
  54.     // 通过键盘输入数据创建图
  55.     graph.createGraphFromInput();
  56.     // 输出到文件Graph1_out.txt
  57.     graph.outputGraphToFile("Graph1_out.txt");
  58.     // 从文件中读取数据创建图
  59.     Graph graphFromFile;
  60.     graphFromFile.createGraphFromFile("Graph1.txt");
  61.     // 输出到文件Graph1_out.txt
  62.     graphFromFile.outputGraphToFile("Graph1_out.txt");
  63.     return 0;
  64. }
复制代码

在上面的代码中,我们首先定义了一个Graph类,它使用邻接表来表示图。通过addEdge函数,我们可以添加边。createGraphFromInput函数用于通过键盘输入数据创建图,createGraphFromFile函数用于从文件中读取数据创建图,并且outputGraphToFile函数用于将图的数据输出到文件。

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

球一个最佳答案谢谢啦!这对我非常重要!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-22 03:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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