C ++程序为给定的固定角度序列生成图
这是一个C++程序,表示给定度数序列的无向图。该算法的时间复杂度为O(v*v),并且不包括自边缘和多个边缘。
算法
Begin To create the graph, Create the first loop to connect each vertex ‘i’. Create second nested loop to connect the vertex ‘i’ to every valid vertex ‘j’, next to it. If the degree of vertex ‘i’ and ‘j’ are more than zero, then connect them. Print the adjacency matrix using PrintMatrix(). End
范例程式码
#include<iostream>
#include<iomanip>
using namespace std;
void PrintMatrix(int matrix[][20], int n) {
int i, j;
cout<<"\n\n"<<setw(3)<<" ";
for(i = 0; i < n; i++)
cout<<setw(3)<<"("<<i+1<<")";
cout<<"\n\n";
for(i = 0; i < n; i++) {
cout<<setw(4)<<"("<<i+1<<")";
for(j = 0; j < n; j++) {
cout<<setw(5)<<matrix[i][j];
}
cout<<"\n\n";
}
}
int main() {
int N, i, j, AdjMat[20][20] = {0};
cout<<"Enter the number of vertex in the graph: ";
cin>>N;
int degseq[N];
for(i = 0; i < N; i++) {
cout<<"Enter the degree of "<<i+1<<" vertex: ";
cin>>degseq[i];
}
for(i = 0; i < N; i++) {
for(j = i+1; j < N; j++) {
(degseq[i] > 0 && degseq[j] > 0) {
degseq[i]--;
degseq[j]--;
AdjMat[i][j] = 1;
AdjMat[j][i] = 1;
}
}
}
PrintMatrix(AdjMat, N);
}输出结果
Enter the number of vertexes of the graph: 5 Enter the number of edges of the graph: 4 Enter the vertex pair for edge 1 V(1): 2 V(2): 1 Enter the vertex pair for edge 2 V(1): 3 V(2): 2 Enter the vertex pair for edge 3 V(1): 1 V(2): 1 Enter the vertex pair for edge 4 V(1): 3 V(2): 1 (1) (2) (3) (4) (5) (1) 0 1 1 1 1 (2) 1 0 0 1 0 (3) 1 0 0 0 0 (4) 1 1 0 0 1 (5) 1 0 0 1 0
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬