Skip to content

Instantly share code, notes, and snippets.

@dennisbot
Created June 23, 2017 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dennisbot/dce7485ddd2e8227977201e14604b172 to your computer and use it in GitHub Desktop.
Save dennisbot/dce7485ddd2e8227977201e14604b172 to your computer and use it in GitHub Desktop.
Implementación de un Grafo con Matrices e incluye método para buscar alcance mínimo a otros vértices
class Graph {
private:
int **G;
int size;
public:
Graph(int n) {
n++;
G = new int*[n];
for (int i = 0; i < n; i++) {
G[i] = (int*)calloc(n, sizeof(int));
// G[i] = new int[n];
}
this->size = n;
}
~Graph() {
for (int i = 0; i < this->size; i++) {
delete G[i];
}
delete G;
}
void showGraph() {
cout << " \t";
for (int i = 0; i < this->size; i++) {
cout << i << "\t";
}
cout << endl;
cout << " \t";
for (int i = 0; i < this->size; i++) {
cout << "=\t";
}
cout << endl;
for (int i = 0; i < this->size; i++) {
cout << "i = " << i << "\t";
for (int j = 0; j < this->size; j++) {
cout << G[i][j] << "\t";
}
cout << endl;
}
}
void add_edge(int u, int v) {
G[u][v] = G[v][u] = 1;
}
vector<int> shortest_reach(int start) {
// this->showGraph();
queue< int > q;
vector<int> nodes(this->size, 0);
q.push(start);
nodes[start] = 1;
int u;
while (!q.empty()) {
u = q.front();
q.pop();
for (int v = 1; v < this->size; v++) {
if (G[u][v] && !nodes[v]) {
nodes[v] = nodes[u] + 1;
q.push(v);
}
}
}
return nodes;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment