graphm.h

本文详细介绍了如何使用C++语言通过邻接矩阵来表示图,并实现了基本的操作,如查找边、获取下一个边等。通过实例演示了如何在图中查找路径并打印图的所有边。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 1. 二维数组存储边的权值, 权为零表示边不存在 */

#ifndef		GRAPHM_H
#define		GRAPHM_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 edge
			if (i == numVertex-1) 
				return false;
		}
	}

	bool NextEdge(Edge preEdge, Edge &myEdge) {	
		myEdge.from = preEdge.from;
		int i;
		
		// last edge haven't next edge
		if (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 edge
				if (i == numVertex-1)
					return false;
			}
		}
		else
			return 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值