矩阵实现无权图

7 篇文章 0 订阅
#pragma once
#include<iostream>
#include <vector>
#include <cassert>
#include <queue>
using namespace std;
class DenseGraph
{
public:
	DenseGraph(int n, bool directed);
	~DenseGraph();
	int V() { return n; }
	int E() { return m; }
	void addEdge(int v,int w);
	bool hasEdge(int v, int w)
	{
		assert(v < n&&v >= 0);
		assert(w < n&&w >= 0);
		return g[v][w];
	}
	void showEdge(int v)
	{
		for (int i = 0; i < n; i++)
		{
			if (g[v][i]==true)
			{
				cout << i << " ";
			}
		}
		cout << endl;
	}
	void BFS(int v)
	{
		assert(v >= 0 && v < n);
		queue<int>q;
		q.push(v);
		visited[v];
		while (!q.empty())
		{
			int qFront = q.front();
			cout << qFront << " ";
			q.pop();
			for (int i = 0; i < n; i++)
			{
				if (g[qFront][i]!=false&&!visited[i])
				{					
					q.push(i);
					visited[i]=true;
				}
			}
		}
		fill(visited, visited + n, false);
	}
	void DFS(int v)
	{
		for (int i=0;i<n;i++)
		{
			if (!visited[i]&&g[v][i])
			{
				dfs(i);
			}
		}
		fill(visited, visited + n, false);
	}
private:
	int n, m;//m代表边数
	bool *visited;
	bool directed;
	void dfs(int v);
	vector<vector<bool>> g;
};

DenseGraph::DenseGraph(int n,bool directed)
{
	this->n = n;
	m = 0;
	this->directed = directed;
	visited = new bool[n];
	for (int i = 0; i < n; i++)
	{
		g.push_back(vector<bool>(n, false));
		visited[i] = false;
	}
}

DenseGraph::~DenseGraph()
{
	delete[]visited;
}

inline void DenseGraph::addEdge(int v, int w)
{
	assert(v >= 0 && w >= 0&&v<n&&w<n);
	if (g[v][w] == true||v==w)
	{
		return;
	}
	else
	{
		g[v][w] = true;
		m++;
	}
	if (!directed)
	{
		g[w][v] = true;
	}
}

inline void DenseGraph::dfs(int v)
{
	visited[v] = true;
	cout << v << " ";
	for (int i = 0; i < n; i++)
	{
		if (!visited[i]&&g[v][i])
		{
			dfs(i);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值