#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);
}
}
}
矩阵实现无权图
最新推荐文章于 2022-06-01 22:32:08 发布