当前位置: 代码迷 >> 综合 >> 大话数据结构学习笔记(9) C++实现邻接矩阵
  详细解决方案

大话数据结构学习笔记(9) C++实现邻接矩阵

热度:90   发布时间:2024-02-27 19:28:37.0
#include<iostream>
#include<vector>
using namespace std;typedef int T;					//顶点的值的类型int,char,double and so on
class Node					//顶点类
{
public:	T value;			        //顶点值int numbers;			        //顶点编号
};class Edge					//边类
{
public:int num1;				//起始顶点int num2;				//终止顶点int weight;			        //权值
};class Graph
{
private:int vertex_nums;			//顶点数int edge_nums;				//边数vector<Node> vertex;			//顶点表vector<Edge> edge;			//边表vector<vector<int>> edge_maze;          //邻接矩阵
public:Graph(int n = 10, int m = 10):vertex_nums(n), edge_nums(m){for (int i = 0; i < vertex_nums; i++)	//顶点表初始化{Node a;a.numbers = i;a.value = 0;vertex.push_back(a);}for (int i = 0; i < vertex_nums; i++)		  //邻接矩阵初始化{vector<int> temp(vertex_nums, 0);edge_maze.push_back(temp);}cout << "please input the edges about the graph:vertex_number1 vertex_number2 weight" << endl;int x, y, z;for (int i = 0; i < edge_nums; i++){cin >> x>>y>>z;Edge edge_temp;edge_temp.num1 = x;edge_temp.num2 = y;edge_temp.weight = z;edge.push_back(edge_temp);edge_maze[x][y] = edge_maze[y][x] = 1;}}void print_edge_maze()					   //邻接矩阵显示{cout << endl;cout << "输出邻接矩阵" << endl;cout << "   ";for (int i = 0; i < vertex_nums; i++){cout << "v" << i << " ";}cout << endl;for (int i = 0; i < vertex_nums; i++){cout << "v" << i << "  ";for (int j = 0; j < vertex_nums; j++){cout << edge_maze[i][j] << "  ";}cout << endl;}}void print_edge_vec()					//输出边表{cout << "输出边表:" << endl;cout << "起始顶点" << "-->" << "结束顶点" << " " << "权值" << endl;for (int i = 0; i < edge_nums; i++){cout << " " << "v" << edge[i].num1 << "     " << "-->" << "  v" << edge[i].num2 << "     " << edge[i].weight << endl;}}
};void main()
{Graph graph(8, 10);graph.print_edge_vec();graph.print_edge_maze();system("pause");
}