logo

Хјерхолцеров алгоритам за усмерени граф

Дати усмерени Ојлеров граф задатак је да се одштампа а Ојлерово коло . Ојлерово коло је путања која прелази сваку ивицу графа тачно једном и та се путања завршава на почетном врху.

Напомена: Дати график садржи Ојлерово коло.

Пример:



Улаз: Усмерени граф

Хјерхолцеров алгоритам за усмерени граф' title=

Излаз: 0 3 4 0 2 1 0

Предуслови:

  • Разговарали смо о проблем проналажења да ли је дати граф Ојлеров или не за неусмерени граф
  • Услови за Ојлерово коло у усмереном Грпаг : (1) Сви врхови припадају једној јако повезаној компоненти. (2) Сви врхови имају исти унутрашњи и излазни степен. Имајте на уму да је за неусмерени граф услов другачији (сви врхови имају паран степен)

приступ:

  1. Изаберите било који почетни врх в и пратите траг ивица од тог темена до повратка на в. Није могуће заглавити у било ком врху осим в јер степен и ванстепен сваког темена морају бити исти када траг уђе у други врх в мора постојати неискоришћена ивица која напушта в. Овако формирана турнеја је затворена, али можда неће обухватити све врхове и ивице почетног графа.
  2. Све док постоји врх у који припада тренутном обиласку, али који има суседне ивице које нису део обиласка, започните другу стазу од у пратећи неискоришћене ивице све док се не вратите на у и придружите турнеји формираној на овај начин претходном обиласку.

Илустрација:

Узимајући пример горњег графикона са 5 чворова: адј = {{2 3} {0} {1} {4} {0}}.

  1. Почните од темена 0 :
    • Тренутна путања: [0]
    • Круг: []
  2. Тема 0 → 3 :
    • Тренутни пут: [0 3]
    • Круг: []
  3. Тема 3 → 4 :
    • Тренутни пут: [0 3 4]
    • Круг: []
  4. Тема 4 → 0 :
    • Тренутни пут: [0 3 4 0]
    • Круг: []
  5. Тема 0 → 2 :
    • Тренутни пут: [0 3 4 0 2]
    • Круг: []
  6. Тема 2 → 1 :
    • Тренутни пут: [0 3 4 0 2 1]
    • Круг: []
  7. Теме 1 → 0 :
    • Тренутни пут: [0 3 4 0 2 1 0]
    • Круг: []
  8. Повратак на врх 0 : Додајте 0 у коло.
    • Тренутни пут: [0 3 4 0 2 1]
    • Круг: [0]
  9. Повратак на врх 1 : Додајте 1 у коло.
    • Тренутни пут: [0 3 4 0 2]
    • Круг: [0 1]
  10. Повратак на врх 2 : Додајте 2 у коло.
    • Тренутни пут: [0 3 4 0]
    • Круг: [0 1 2]
  11. Повратак на врх 0 : Додајте 0 у коло.
    • Тренутни пут: [0 3 4]
    • Круг: [0 1 2 0]
  12. Повратак на врх 4 : Додајте 4 кругу.
    • Тренутни пут: [0 3]
    • Круг: [0 1 2 0 4]
  13. Повратак на врх 3 : Додајте 3 у коло.
    • Тренутна путања: [0]
    • Круг: [0 1 2 0 4 3]
  14. Повратак на врх 0 : Додајте 0 у коло.
    • Тренутна путања: []
    • Круг: [0 1 2 0 4 3 0]

Испод је имплементација за горњи приступ: 

C++
// C++ program to print Eulerian circuit in given // directed graph using Hierholzer algorithm #include    using namespace std; // Function to print Eulerian circuit vector<int> printCircuit(vector<vector<int>> &adj) {  int n = adj.size();  if (n == 0)  return {};  // Maintain a stack to keep vertices  // We can start from any vertex here we start with 0  vector<int> currPath;  currPath.push_back(0);  // list to store final circuit  vector<int> circuit;  while (currPath.size() > 0) {  int currNode = currPath[currPath.size() - 1];  // If there's remaining edge in adjacency list  // of the current vertex  if (adj[currNode].size() > 0) {    // Find and remove the next vertex that is  // adjacent to the current vertex  int nextNode = adj[currNode].back();  adj[currNode].pop_back();  // Push the new vertex to the stack  currPath.push_back(nextNode);  }  // back-track to find remaining circuit  else {  // Remove the current vertex and  // put it in the circuit  circuit.push_back(currPath.back());  currPath.pop_back();  }  }  // reverse the result vector   reverse(circuit.begin() circuit.end());    return circuit; } int main() {  vector<vector<int>> adj = {{2 3} {0} {1} {4} {0}};  vector<int> ans = printCircuit(adj);    for (auto v: ans) cout << v << ' ';  cout << endl;  return 0; } 
Java
// Java program to print Eulerian circuit in given // directed graph using Hierholzer algorithm import java.util.*; class GfG {  // Function to print Eulerian circuit  static List<Integer> printCircuit(List<List<Integer>> adj) {  int n = adj.size();  if (n == 0)  return new ArrayList<>();  // Maintain a stack to keep vertices  // We can start from any vertex here we start with 0  List<Integer> currPath = new ArrayList<>();  currPath.add(0);  // list to store final circuit  List<Integer> circuit = new ArrayList<>();  while (currPath.size() > 0) {  int currNode = currPath.get(currPath.size() - 1);  // If there's remaining edge in adjacency list  // of the current vertex  if (adj.get(currNode).size() > 0) {  // Find and remove the next vertex that is  // adjacent to the current vertex  int nextNode = adj.get(currNode).get(adj.get(currNode).size() - 1);  adj.get(currNode).remove(adj.get(currNode).size() - 1);  // Push the new vertex to the stack  currPath.add(nextNode);  }  // back-track to find remaining circuit  else {  // Remove the current vertex and  // put it in the circuit  circuit.add(currPath.get(currPath.size() - 1));  currPath.remove(currPath.size() - 1);  }  }  // reverse the result vector  Collections.reverse(circuit);  return circuit;  }  public static void main(String[] args) {  List<List<Integer>> adj = new ArrayList<>();  adj.add(new ArrayList<>(Arrays.asList(2 3)));  adj.add(new ArrayList<>(Arrays.asList(0)));   adj.add(new ArrayList<>(Arrays.asList(1)));   adj.add(new ArrayList<>(Arrays.asList(4)));   adj.add(new ArrayList<>(Arrays.asList(0)));   List<Integer> ans = printCircuit(adj);  for (int v : ans) System.out.print(v + ' ');  System.out.println();  } } 
Python
# Python program to print Eulerian circuit in given # directed graph using Hierholzer algorithm # Function to print Eulerian circuit def printCircuit(adj): n = len(adj) if n == 0: return [] # Maintain a stack to keep vertices # We can start from any vertex here we start with 0 currPath = [0] # list to store final circuit circuit = [] while len(currPath) > 0: currNode = currPath[-1] # If there's remaining edge in adjacency list # of the current vertex if len(adj[currNode]) > 0: # Find and remove the next vertex that is # adjacent to the current vertex nextNode = adj[currNode].pop() # Push the new vertex to the stack currPath.append(nextNode) # back-track to find remaining circuit else: # Remove the current vertex and # put it in the circuit circuit.append(currPath.pop()) # reverse the result vector circuit.reverse() return circuit if __name__ == '__main__': adj = [[2 3] [0] [1] [4] [0]] ans = printCircuit(adj) for v in ans: print(v end=' ') print() 
C#
// C# program to print Eulerian circuit in given // directed graph using Hierholzer algorithm using System; using System.Collections.Generic; class GfG {    // Function to print Eulerian circuit  static List<int> printCircuit(List<List<int>> adj) {  int n = adj.Count;  if (n == 0)  return new List<int>();  // Maintain a stack to keep vertices  // We can start from any vertex here we start with 0  List<int> currPath = new List<int> { 0 };  // list to store final circuit  List<int> circuit = new List<int>();  while (currPath.Count > 0) {  int currNode = currPath[currPath.Count - 1];  // If there's remaining edge in adjacency list  // of the current vertex  if (adj[currNode].Count > 0) {  // Find and remove the next vertex that is  // adjacent to the current vertex  int nextNode = adj[currNode][adj[currNode].Count - 1];  adj[currNode].RemoveAt(adj[currNode].Count - 1);  // Push the new vertex to the stack  currPath.Add(nextNode);  }  // back-track to find remaining circuit  else {  // Remove the current vertex and  // put it in the circuit  circuit.Add(currPath[currPath.Count - 1]);  currPath.RemoveAt(currPath.Count - 1);  }  }  // reverse the result vector  circuit.Reverse();  return circuit;  }  static void Main(string[] args) {  List<List<int>> adj = new List<List<int>> {  new List<int> { 2 3 }  new List<int> { 0 }  new List<int> { 1 }  new List<int> { 4 }  new List<int> { 0 }  };  List<int> ans = printCircuit(adj);  foreach (int v in ans) {  Console.Write(v + ' ');  }  Console.WriteLine();  } } 
JavaScript
// JavaScript program to print Eulerian circuit in given // directed graph using Hierholzer algorithm // Function to print Eulerian circuit function printCircuit(adj) {  let n = adj.length;  if (n === 0)  return [];  // Maintain a stack to keep vertices  // We can start from any vertex here we start with 0  let currPath = [0];  // list to store final circuit  let circuit = [];  while (currPath.length > 0) {  let currNode = currPath[currPath.length - 1];  // If there's remaining edge in adjacency list  // of the current vertex  if (adj[currNode].length > 0) {  // Find and remove the next vertex that is  // adjacent to the current vertex  let nextNode = adj[currNode].pop();  // Push the new vertex to the stack  currPath.push(nextNode);  }  // back-track to find remaining circuit  else {  // Remove the current vertex and  // put it in the circuit  circuit.push(currPath.pop());  }  }  // reverse the result vector  circuit.reverse();  return circuit; } let adj = [[2 3] [0] [1] [4] [0]]; let ans = printCircuit(adj); for (let v of ans) {  console.log(v ' '); } 

Излаз
0 3 4 0 2 1 0 

Временска сложеност:  О(В + Е) где је В број темена, а Е број ивица у графу. Разлог за то је зато што алгоритам врши претрагу у дубину (ДФС) и посећује сваки врх и сваку ивицу тачно једном. Дакле, за сваки врх је потребно О(1) времена да га посети, а за сваку ивицу је потребно О(1) времена да га пређе.

Сложеност простора  : О(В + Е) као алгоритам користи стек за складиштење тренутне путање и листу за складиштење коначног кола. Максимална величина стека може бити В + Е у најгорем случају, тако да је комплексност простора О(В + Е).

Креирај квиз