fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,125 @@
---
title: Breadth First Search (BFS)
localeTitle: Primera búsqueda de amplitud (BFS)
---
## Primera búsqueda de amplitud (BFS)
Breadth First Search es uno de los algoritmos gráficos más simples. Atraviesa el gráfico al verificar primero el nodo actual y luego expandirlo agregando sus sucesores al siguiente nivel. El proceso se repite para todos los nodos en el nivel actual antes de pasar al siguiente nivel. Si se encuentra la solución, la búsqueda se detiene.
### Visualización
![](https://upload.wikimedia.org/wikipedia/commons/4/46/Animated_BFS.gif)
### Evaluación
Complejidad del espacio: O (n)
Peor caso complejidad del tiempo: O (n)
La primera búsqueda de amplitud se completa en un conjunto finito de nodos y es óptima si el costo de pasar de un nodo a otro es constante.
### Código C ++ para implementación BFS
```cpp
// Program to print BFS traversal from a given
// source vertex. BFS(int s) traverses vertices
// reachable from s.
#include<iostream>
#include <list>
using namespace std;
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
list<int> *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v's list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
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);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}
```
#### Más información:
[Graficas](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Primera búsqueda de profundidad (DFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md)

View File

@ -0,0 +1,105 @@
---
title: Depth First Search (DFS)
localeTitle: Primera búsqueda de profundidad (DFS)
---
## Primera búsqueda de profundidad (DFS)
Depth First Search es uno de los algoritmos gráficos más simples. Atraviesa el gráfico, primero verifica el nodo actual y luego se mueve a uno de sus sucesores para repetir el proceso. Si el nodo actual no tiene un sucesor para verificar, volvemos a su predecesor y el proceso continúa (al pasar a otro sucesor). Si se encuentra la solución, la búsqueda se detiene.
### Visualización
![](https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif)
### Implementación (C ++ 14)
\`\` \`c ++
# incluir
# incluir
# incluir
# incluir
utilizando namespace std;
clase grafica { En televisión; // número de vértices
```
// pointer to a vector containing adjacency lists
vector < int > *adj;
```
público: Gráfico (int v); // Constructor
```
// function to add an edge to graph
void add_edge(int v, int w);
// prints dfs traversal from a given source `s`
void dfs();
void dfs_util(int s, vector < bool> &visited);
```
};
Graph :: Graph (int v) { esto -> v = v; adj = nuevo vector <int> \[v\]; }
void Graph :: add _edge (int u, int v) { adj \[u\]. empujar_ hacia atrás (v); // agregar v a la lista de u adj \[v\] .push _atrás (v); // agregar u a la lista de v (elimine esta declaración si se dirige el gráfico) } Gráfica de vacío: dfs () { // vector visitado - para realizar un seguimiento de los nodos visitados durante DFS vector <bool> visitado (v, falso); // marcando todos los nodos / vértices como no visitados para (int i = 0; i <v; i ++) si (! visitó \[i\]) dfs_ util (i, visitó); } // ¡note el uso de llamada por referencia aquí! void Graph :: dfs\_util (int s, vector <bool> & visited) { // marca el nodo / vértice actual como visitado visitó \[s\] = verdadero; // salida a la salida estándar (pantalla) cout << s << "";
```
// traverse its adjacency list and recursively call dfs_util for all of its neighbours!
// (only if the neighbour has not been visited yet!)
for(vector < int > :: iterator itr = adj[s].begin(); itr != adj[s].end(); itr++)
if(!visited[*itr])
dfs_util(*itr, visited);
```
}
int main () { // crear un gráfico utilizando la clase de gráfico que definimos anteriormente Gráfica g (4); _borde_ g.add _(0, 1);_ borde _g.add_ (0, 2); g.add _borde (1, 2);_ borde _g.add_ (2, 0); g.add _borde (2, 3); g.add_ borde (3, 3);
```
cout << "Following is the Depth First Traversal of the provided graph"
<< "(starting from vertex 0): ";
g.dfs();
// output would be: 0 1 2 3
return 0;
```
}
```
### Evaluation
Space Complexity: O(n)
Worse Case Time Complexity: O(n)
Depth First Search is complete on a finite set of nodes. I works better on shallow trees.
### Implementation of DFS in C++
```
c ++
# incluir
# incluir
# incluir
utilizando namespace std;
struct Graph { En televisión; bool \* _adj; público: Gráfico (int vcount); void addEdge (int u, int v); void deleteEdge (int u, int v); vector_ _DFS (int s); void DFSUtil (int s, vector_ _& dfs, vector_ _&visitó); }; Graph :: Graph (int vcount) { esto-> v = vcount; this-> adj = new bool_ \[vcount\]; para (int i = 0; i
void Graph :: addEdge (int u, int w) { this-> adj \[u\] \[w\] = true; this-> adj \[w\] \[u\] = true; }
void Graph :: deleteEdge (int u, int w) { esto-> adj \[u\] \[w\] = falso; esto-> adj \[w\] \[u\] = falso; }
Void Graph :: DFSUtil (int s, vector & dfs, vector &visitó){ visitó \[s\] = verdadero; dfs.push\_back (s); para (int i = 0; i v; i ++) { if (this-> adj \[s\] \[i\] == true && visitó \[i\] == false) DFSUtil (i, dfs, visitó); } }
vector Graph :: DFS (int s) { vector visitado (this-> v); vector dfs; DFSUtil (s, dfs, visitó); devuelve dfs; } \`\` \`
#### Más información:
[Graficas](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Primera búsqueda de amplitud (BFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/breadth-first-search/index.md)
[Primera búsqueda en profundidad (DFS) - Wikipedia](https://en.wikipedia.org/wiki/Depth-first_search)

View File

@ -0,0 +1,95 @@
---
title: Dijkstra's Algorithm
localeTitle: El algoritmo de Dijkstra
---
# El algoritmo de Dijkstra
El algoritmo de Dijkstra es un algoritmo gráfico presentado por EW Dijkstra. Encuentra la ruta más corta de una sola fuente en un gráfico con bordes no negativos (¿por qué?)
Creamos 2 matrices: visitada y distancia, que registran si un vértice es visitado y cuál es la distancia mínima desde el vértice de origen respectivamente. La matriz inicialmente visitada se asigna como falsa y la distancia como infinita.
Partimos del vértice fuente. Deje que el vértice actual sea u y sus vértices adyacentes sean v. Ahora, para cada v adyacente a u, la distancia se actualiza si no se ha visitado antes y la distancia desde u es menor que su distancia actual. Luego seleccionamos el siguiente vértice con la menor distancia y que no ha sido visitado.
La cola de prioridad se usa a menudo para cumplir con este último requisito en el menor tiempo posible. A continuación se muestra una implementación de la misma idea utilizando la cola de prioridad en Java.
```java
import java.util.*;
public class Dijkstra {
class Graph {
LinkedList<Pair<Integer>> adj[];
int n; // Number of vertices.
Graph(int n) {
this.n = n;
adj = new LinkedList[n];
for(int i = 0;i<n;i++) adj[i] = new LinkedList<>();
}
// add a directed edge between vertices a and b with cost as weight
public void addEdgeDirected(int a, int b, int cost) {
adj[a].add(new Pair(b, cost));
}
public void addEdgeUndirected(int a, int b, int cost) {
addEdgeDirected(a, b, cost);
addEdgeDirected(b, a, cost);
}
}
class Pair<E> {
E first;
E second;
Pair(E f, E s) {
first = f;
second = s;
}
}
// Comparator to sort Pairs in Priority Queue
class PairComparator implements Comparator<Pair<Integer>> {
public int compare(Pair<Integer> a, Pair<Integer> b) {
return a.second - b.second;
}
}
// Calculates shortest path to each vertex from source and returns the distance
public int[] dijkstra(Graph g, int src) {
int distance[] = new int[gn]; // shortest distance of each vertex from src
boolean visited[] = new boolean[gn]; // vertex is visited or not
Arrays.fill(distance, Integer.MAX_VALUE);
Arrays.fill(visited, false);
PriorityQueue<Pair<Integer>> pq = new PriorityQueue<>(100, new PairComparator());
pq.add(new Pair<Integer>(src, 0));
distance[src] = 0;
while(!pq.isEmpty()) {
Pair<Integer> x = pq.remove(); // Extract vertex with shortest distance from src
int u = x.first;
visited[u] = true;
Iterator<Pair<Integer>> iter = g.adj[u].listIterator();
// Iterate over neighbours of u and update their distances
while(iter.hasNext()) {
Pair<Integer> y = iter.next();
int v = y.first;
int weight = y.second;
// Check if vertex v is not visited
// If new path through u offers less cost then update distance array and add to pq
if(!visited[v] && distance[u]+weight<distance[v]) {
distance[v] = distance[u]+weight;
pq.add(new Pair(v, distance[v]));
}
}
}
return distance;
}
public static void main(String args[]) {
Dijkstra d = new Dijkstra();
Dijkstra.Graph g = d.new Graph(4);
g.addEdgeUndirected(0, 1, 2);
g.addEdgeUndirected(1, 2, 1);
g.addEdgeUndirected(0, 3, 6);
g.addEdgeUndirected(2, 3, 1);
g.addEdgeUndirected(1, 3, 3);
int dist[] = d.dijkstra(g, 0);
System.out.println(Arrays.toString(dist));
}
}
```

View File

@ -0,0 +1,48 @@
---
title: Floyd Warshall Algorithm
localeTitle: Floyd Warshall Algorithm
---
## Floyd Warshall Algorithm
El algoritmo Floyd Warshall es un gran algoritmo para encontrar la distancia más corta entre todos los vértices en la gráfica. Tiene un algoritmo muy conciso y complejidad de tiempo O (V ^ 3) (donde V es el número de vértices). Puede utilizarse con pesos negativos, aunque los ciclos de peso negativos no deben estar presentes en el gráfico.
### Evaluación
Complejidad del espacio: O (V ^ 2)
Peor complejidad de tiempo del caso: O (V ^ 3)
### Implementacion Python
```python
# A large value as infinity
inf = 1e10
def floyd_warshall(weights):
V = len(weights)
distance_matrix = weights
for k in range(V):
next_distance_matrix = [list(row) for row in distance_matrix] # make a copy of distance matrix
for i in range(V):
for j in range(V):
# Choose if the k vertex can work as a path with shorter distance
next_distance_matrix[i][j] = min(distance_matrix[i][j], distance_matrix[i][k] + distance_matrix[k][j])
distance_matrix = next_distance_matrix # update
return distance_matrix
# A graph represented as Adjacency matrix
graph = [
[0, inf, inf, -3],
[inf, 0, inf, 8],
[inf, 4, 0, -2],
[5, inf, 3, 0]
]
print(floyd_warshall(graph))
```
#### Más información:
[Graficas](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Floyd Warshall - Wikipedia](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm)

View File

@ -0,0 +1,23 @@
---
title: Graph algorithms
localeTitle: Algoritmos de grafos
---
## Algoritmos de grafos
Los algoritmos de gráficos son un conjunto de instrucciones que atraviesan (visitan los nodos de a) gráficos.
Algunos algoritmos se utilizan para encontrar un nodo específico o la ruta entre dos nodos dados.
### ¿Por qué los algoritmos de grafos son importantes?
Los gráficos son estructuras de datos muy útiles que pueden servir para modelar varios problemas. Estos algoritmos tienen aplicaciones directas en sitios de redes sociales, modelado de máquinas de estados y muchos más.
### Algún algoritmo de grafo común
Algunos de los algoritmos de grafos más comunes son:
[Graficas](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Primera búsqueda de amplitud (BFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/breadth-first-search/index.md)
[Primera búsqueda de profundidad (DFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md)