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: Первый поиск Breadth (BFS)
---
## Первый поиск Breadth (BFS)
Breadth First Search - один из самых простых алгоритмов графа. Он пересекает график, сначала проверяя текущий узел, а затем расширяя его, добавляя своих преемников на следующий уровень. Процесс повторяется для всех узлов текущего уровня, прежде чем перейти на следующий уровень. Если решение найдено, поиск останавливается.
### Визуализация
![](https://upload.wikimedia.org/wikipedia/commons/4/46/Animated_BFS.gif)
### оценка
Космическая сложность: O (n)
Хуже того, сложность времени: O (n)
Breadth First Search завершен на конечном множестве узлов и оптимален, если стоимость перехода от одного узла к другому постоянна.
### Код C ++ для реализации 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;
}
```
#### Дополнительная информация:
[диаграммы](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Глубина первого поиска (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: Глубина первого поиска (DFS)
---
## Глубина первого поиска (DFS)
Depth First Search - один из самых простых алгоритмов графа. Он пересекает график, сначала проверяя текущий узел, а затем переходя к одному из его помощников, чтобы повторить процесс. Если в текущем узле нет помощника для проверки, мы возвращаемся к его предшественнику, и процесс продолжается (перейдя к другому помощнику). Если решение найдено, поиск останавливается.
### Визуализация
![](https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif)
### Реализация (C ++ 14)
\`\` \`C ++
# включают
# включают
# включают
# включают
использование пространства имен std;
класс Graph { на телевидении; // количество вершин
```
// pointer to a vector containing adjacency lists
vector < int > *adj;
```
общественности: График (int v); // Конструктор
```
// 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) { это -> v = v; adj = новый вектор <int> \[v\]; }
void Graph :: add _edge (int u, int v) { adj \[u\] .push_ назад (v); // добавьте v в список u adj \[v\] .push азад (v); // добавим u в список v (удалите этот оператор, если график направлен!) } void Graph :: dfs () { // посещаемый вектор - отслеживать посещаемые узлы во время DFS вектор <bool> посещен (v, false); // маркировка всех узлов / вершин как не посещенных for (int i = 0; i <v; i ++) если (! посещаемые \[я\]) dfs_ util (i, посещенный); } // обратите внимание на использование вызова по ссылке здесь! void Graph :: dfs\_util (int s, vector <bool> & visited) { // пометить текущий узел / вершину как посещенный \[s\] = true; // выводим его на стандартный вывод (экран) 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 () { // создаем граф, используя класс Graph, который мы определили выше График g (4); g.add _edge (0, 1); g.add_ edge (0, 2); g.add _edge (1, 2); g.add_ edge (2, 0); g.add _edge (2, 3); g.add_ edge (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 ++
# включают
# включают
# включают
использование пространства имен std;
struct Graph { на телевидении; bool \* _adj; общественности: График (int vcount); void addEdge (int u, int v); void deleteEdge (int u, int v); вектор_ _DFS (int s); void DFSUtil (int s, vector_ _& ДФС, вектор_ _и посетил); }; Graph :: Graph (int vcount) { this-> v = vcount; this-> adj = new bool_ \[vcount\]; для (int i = 0; i
void Graph :: addEdge (int u, int w) { this-> прил \[и\] \[ш\] = TRUE; this-> прил \[ш\] \[и\] = TRUE; }
void Graph :: deleteEdge (int u, int w) { this-> прил \[и\] \[ш\] = ложь; this-> прил \[ж\] \[и\] = ложь; }
void Graph :: DFSUtil (int s, vector & dfs, вектор И посетил) { посетил \[с\] = TRUE; dfs.push\_back (ы); для (int i = 0; i v; я ++) { if (this-> adj \[s\] \[i\] == true && visited \[i\] == false) Dfsutil (я, ДФС, посетил); } }
вектор Graph :: DFS (int s) { вектор посетил (this-> v); вектор ДФС; Dfsutil (s, ДФС, посетили); return dfs; } \`\` \`
#### Дополнительная информация:
[диаграммы](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Первый поиск Breadth (BFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/breadth-first-search/index.md)
[Глубина первого поиска (DFS) - Википедия](https://en.wikipedia.org/wiki/Depth-first_search)

View File

@@ -0,0 +1,95 @@
---
title: Dijkstra's Algorithm
localeTitle: Алгоритм Дейкстры
---
# Алгоритм Дейкстры
Алгоритм Дейкстры - это алгоритм графа, представленный Е. В. Дейкстром. Он находит кратчайший путь одного источника в графе с неотрицательными ребрами (почему?)
Мы создаем 2 массива: посещенные и удаленные, которые фиксируют, посещена ли вершина и каково минимальное расстояние от исходной вершины соответственно. Первоначально посещаемый массив присваивается как ложный и дальний как бесконечный.
Мы начинаем с исходной вершины. Пусть текущая вершина равна u, а ее смежные вершины - v. Теперь для каждого v, смежного с u, расстояние обновляется, если оно не было посещено раньше, а расстояние от u меньше его текущего расстояния. Затем мы выбираем следующую вершину с наименьшим расстоянием и которая не была посещена.
Приоритетная очередь часто используется для удовлетворения этого последнего требования за минимальное время. Ниже приведена реализация одной и той же идеи с использованием очереди приоритетов в 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: Алгоритм Флойда Варшалла
---
## Алгоритм Флойда Варшалла
Алгоритм Флойда Варшалла - отличный алгоритм для нахождения кратчайшего расстояния между всеми вершинами в графе. Он имеет очень сжатый алгоритм и временную сложность O (V ^ 3) (где V - число вершин). Его можно использовать с отрицательными весами, хотя отрицательные весовые циклы не должны присутствовать на графике.
### оценка
Космическая сложность: O (V ^ 2)
Хуже того, сложность времени: O (V ^ 3)
### Реализация 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))
```
#### Дополнительная информация:
[диаграммы](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Флойд Варшалл - Википедия](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm)

View File

@@ -0,0 +1,23 @@
---
title: Graph algorithms
localeTitle: Графические алгоритмы
---
## Графические алгоритмы
Графовые алгоритмы представляют собой набор инструкций, которые пересекают (посещает узлы a) графа.
Некоторые алгоритмы используются для поиска определенного узла или пути между двумя заданными узлами.
### Почему алгоритмы графа важны
Графики - очень полезные структуры данных, которые могут быть для моделирования различных проблем. Эти алгоритмы имеют прямые приложения на сайтах Social Networking, State Machine и многие другие.
### Некоторые общие алгоритмы графа
Некоторые из наиболее распространенных алгоритмов графа:
[диаграммы](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
[Первый поиск Breadth (BFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/breadth-first-search/index.md)
[Глубина первого поиска (DFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md)