graphm.h

来源:互联网 发布:二维数组排序 php 编辑:程序博客网 时间:2024/06/10 00:12
/* 1. 二维数组存储边的权值, 权为零表示边不存在 */#ifndefGRAPHM_H#defineGRAPHM_H#include<iostream>#include"graph.h"using namespace std;class Graphm : public Graph {private:int **matrix;public:Graphm(int numVert) : Graph(numVert) {matrix = (int**)new int*[numVertex];for (int i = 0; i < numVertex; i++) matrix[i] = new int[numVertex];for (int i = 0; i < numVertex; i++) for (int j = 0; j < numVertex; j++) matrix[i][j] = 0;}~Graphm() {for (int i = 0; i < numVertex; i++)delete []matrix[i];delete []matrix;}bool FirstEdge(int oneVertex, Edge &myEdge) {myEdge.from = oneVertex;for (int i = 0; i < numVertex; i++) {if (matrix[oneVertex][i] != 0) {myEdge.to = i;myEdge.weight = matrix[oneVertex][i];return true;}// don't find edgeif (i == numVertex-1) return false;}}bool NextEdge(Edge preEdge, Edge &myEdge) {myEdge.from = preEdge.from;int i;// last edge haven't next edgeif (preEdge.to < numVertex-1) {for (i = preEdge.to+1; i < numVertex; i++) {if (matrix[preEdge.from][i] != 0) {myEdge.to = i;myEdge.weight = matrix[preEdge.from][i];return true;}// don't find next edgeif (i == numVertex-1)return false;}}elsereturn false;}void print() {Edge temp, temp1;for (int i = 0; i < numVertex; i++) {if (FirstEdge(i, temp)) { temp.print();while (NextEdge(temp, temp1)) {temp1.print();temp = temp1;}}}}void setEdge(int from, int to, int weight) {if (matrix[from][to] <= 0) {numEdge++;Indegree[to]++;}matrix[from][to] = weight;}void delEdge(int from, int to) {if (matrix[from][to] > 0) {numEdge--;Indegree[to]--;}matrix[from][to] = 0;}}; //class Graphm#endif

#include<iostream>#include"graphm.h"using namespace std;int main() {Graphm g(5);g.setEdge(1, 0, 15); g.setEdge(0, 1, 10);g.setEdge(1, 2, 5);g.setEdge(0, 4, 100);Edge first, next;g.FirstEdge(0, first);first.print();g.NextEdge(first, next);next.print();if (g.isEdge(first))cout<<"first is edge!"<<endl;g.print();return 0;}

0 0
原创粉丝点击