E025. Depth-first search

e-maxx algorithm original: C/C++ #algorithm #dfs #emaxx #graph #search
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

Источник: e-maxx.ru/algo, страница PDF 85.

Это один из основных Algorithmeов на grapheах. В результате поиска в глубину находится лексикоgrapheически первый путь в grapheе. Algorithme работает за O (N+M).

Applications Algorithmeа

● Поиск любого пути в grapheе.

● Поиск лексикоgrapheически первого пути в grapheе.

● Проверка, является ли одна vertex дерева предком другой:

В начале и конце итерации поиска в глубину будет запоминать "время" захода и Sortieа в каждой вершине. Теперь за O (1) можно find ответ: vertex i является предком вершины j тогда и только тогда, когда starti < startj и endi > endj.

● Problème LCA (Lowest common ancestor).

● Topological sorting:

Запускаем серию поисков в глубину, чтобы обойти все вершины grapheа. Отсортируем вершины по времени Sortieа по убыванию - это и будет ответом.

● Проверка grapheа на ацикличность и нахождение цикла

● Поиск компонент сильной связности:

Сначала делаем топологическую сортировку, потом транспонируем graphe и проводим снова серию поисков в глубину в порядке, определяемом топологической сортировкой. Каждое arbre поиска - сильносвязная компонента.

● Поиск мостов:

Сначала превращаем graphe в ориентированный, делая серию поисков в глубину, и ориентируя каждое edge так, как мы пытались по нему пройти. Затем находим сильносвязные компоненты. Мостами являются те рёбра, концы которых принадлежат разным сильносвязным компонентам.

Implémentation

vector < vector<int> > g; // graphe

int n; // number вершин

vector<int> color; // цвет вершины (0, 1, или 2)

vector<int> time_in, time_out; // "времена" захода и Sortieа из вершины
int dfs_timer = 0; // "таймер" для определения времён

void dfs (int v) {

time_in[v] = dfs_timer++;

color[v] = 1;

for (vector<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
if (color[*i] == 0)

dfs (*i);

color[v] = 2;

time_out[v] = dfs_timer++;

} Это наиболее общий код. Во многих случаях времена захода и Sortieа из вершины не важны, так же как и не важны цвета вершин (но тогда надо будет ввести аналогичный по смыслу булевский tableau used). Вот наиболее простая Implémentation:

vector < vector<int> > g; // graphe

int n; // number вершин

vector<char> used;

void dfs (int v) {

used[v] = true;

for (vector<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
if (!used[*i])

dfs (*i);

}

C# solution

brouillon automatique, à relire avant soumission
using System;
using System.Collections.Generic;
using System.Linq;

public static class AlgorithmDraft
{
    // Auto-generated C# draft from the original e-maxx C/C++ listing. Review before production use.
    vector < List<int> > g; // граф
    int n; // число вершин
    List<int> color; // цвет вершины (0, 1, или 2)
    List<int> time_in, time_out; // "времена" захода и выхода из вершины
    int dfs_timer = 0; // "таймер" для определения времён
    void dfs (int v) {
            time_in[v] = dfs_timer++;
            color[v] = 1;
            for (List<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                    if (color[*i] == 0)
                            dfs (*i);
            color[v] = 2;
            time_out[v] = dfs_timer++;
    }
    vector < List<int> > g; // граф
    int n; // число вершин
    List<char> used;
    void dfs (int v) {
            used[v] = true;
            for (List<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                    if (!used[*i])
                            dfs (*i);
    }
}

C++ solution

correspondant/original
vector < vector<int> > g; // граф
int n; // число вершин
vector<int> color; // цвет вершины (0, 1, или 2)
vector<int> time_in, time_out; // "времена" захода и выхода из вершины
int dfs_timer = 0; // "таймер" для определения времён
void dfs (int v) {
        time_in[v] = dfs_timer++;
        color[v] = 1;
        for (vector<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                if (color[*i] == 0)
                        dfs (*i);
        color[v] = 2;
        time_out[v] = dfs_timer++;
}
vector < vector<int> > g; // граф
int n; // число вершин
vector<char> used;
void dfs (int v) {
        used[v] = true;
        for (vector<int>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                if (!used[*i])
                        dfs (*i);
}

Java solution

brouillon automatique, à relire avant soumission
import java.util.*;
import java.math.*;

public class AlgorithmDraft {
    // Auto-generated Java draft from the original e-maxx C/C++ listing. Review before production use.
    vector < ArrayList<Integer> > g; // граф
    int n; // число вершин
    ArrayList<Integer> color; // цвет вершины (0, 1, или 2)
    ArrayList<Integer> time_in, time_out; // "времена" захода и выхода из вершины
    int dfs_timer = 0; // "таймер" для определения времён
    void dfs (int v) {
            time_in[v] = dfs_timer++;
            color[v] = 1;
            for (ArrayList<Integer>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                    if (color[*i] == 0)
                            dfs (*i);
            color[v] = 2;
            time_out[v] = dfs_timer++;
    }
    vector < ArrayList<Integer> > g; // граф
    int n; // число вершин
    ArrayList<Character> used;
    void dfs (int v) {
            used[v] = true;
            for (ArrayList<Integer>::iterator i=g[v].begin(); i!=g[v].end(); ++i)
                    if (!used[*i])
                            dfs (*i);
    }
}

Материал разбит как Algorithmeическая Problème: изучить постановку, понять асимптотику и реализовать Algorithme на выбранном языке.

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.