Ai
1 Star 0 Fork 0

mktime/design-pattern-cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
graph.cpp 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
内部项目 提交于 2021-05-18 13:07 +08:00 . 访问者模式,图的遍历,01背包
#include <iostream>
#include <vector>
#include <cstdio>
#include <list>
#include <queue>
using namespace std;
class Graph{
private:
int V; // 节点数量
list<int>* adj; // 邻接矩阵
int* inDegree; // 入度数组
queue<int>* q; // 入度位0的队列
public:
Graph(int v) {
this->V = v;
this->adj = new list<int>[v];
this->inDegree = new int[v];
for(int i=0; i<v; i++) {
this->inDegree[i] = 0;
}
}
~Graph() {
delete [] this->adj;
delete [] this->inDegree;
}
void addEdge(int v, int w){
this->adj[v].push_back(w);
inDegree[w]++;
}
bool topoSort() {
for (int i=0; i<this->V; i++) {
if (inDegree[i] == 0) {
q->push(i);
}
}
int cnt = 0, v;
while (!q->empty()) {
v = q->front();
q->pop();
printf("%d ", v);
cnt ++;
for (list<int>::iterator i=adj[v].begin(); i!=adj[v].end(); ++i) {
if (!--inDegree[*i]) {
q->push(*i);
}
}
}
if (cnt == 0) {
return true;
}
else {
return false;
}
}
void BFSUtil(int v, bool visited[]) {
queue<int> que;
visited[v] = true;
que.push(v);
int node;
while (!que.empty()) {
node = que.front();
printf("%d ", node);
que.pop();
for(list<int>::iterator i=adj[node].begin(); i!=adj[node].end(); i++) {
if (!visited[*i]) {
visited[*i] = true;
que.push(*i);
}
}
}
}
void BFS(int v) {
bool *visited = new bool[v];
for (int i=0; i<V; i++) {
visited[i] = false;
}
BFSUtil(v, visited);
}
void DFSUtil(int v, bool visited[]) {
}
void DFS(int v) {
}
};
int main(int argc, char** argv) {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mktime/design-pattern-cpp.git
git@gitee.com:mktime/design-pattern-cpp.git
mktime
design-pattern-cpp
design-pattern-cpp
master

搜索帮助