Created
October 17, 2017 04:13
-
-
Save bexp/59473ef3015b938e442c7685844d2832 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <list> | |
#include <stdlib.h> | |
#include <climits> | |
#include <bits/stdc++.h> | |
using namespace std; | |
class graph { | |
public: | |
graph(int v) { | |
V = v; | |
adj = new list<int>[v]; | |
} | |
void addEdge(int u, int v) { | |
adj[u].push_back(v); | |
} | |
void dfs(int v) { | |
bool visited[V] = {}; | |
stack<int> stack; | |
stack.push(v); | |
while (!stack.empty()) { | |
int node = stack.top(); | |
if (!visited[node]) { | |
visited[node] = true; | |
cout << "visited: " << node << endl; | |
} | |
for (auto i : adj[node]) { | |
if (!visited[i]) | |
stack.push(i); | |
} | |
} | |
} | |
void bfs(int v) { | |
bool visited[V] = {}; | |
list<int> queue; | |
queue.push_back(v); | |
visited[v] = true; | |
while (!queue.empty()) { | |
int node = queue.front(); | |
queue.pop_front(); | |
if (!visited[node]) { | |
cout << "visited: " << node << endl; | |
visited[node] = true; | |
for (auto it : adj[node]) { | |
if (!visited[it]) { | |
visited[it] = true; | |
queue.push_back(it); | |
} | |
} | |
} | |
} | |
} | |
~graph() { | |
if (adj != NULL) { | |
delete [] adj; | |
} | |
} | |
private: | |
list<int> *adj; | |
int V; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment