JALLAT_tri_topo.ml 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. (*Ce graphe orienté est représenté par une liste de liste, chaque liste donnant l'arrivée des arretes.*)
  2. (*Dans cet exemple, il existe une arrete de 0 vers 1, donc dans la case 1 du tableau, il y a 0*)
  3. let gex1 = [[];[0];[1;3];[];[3];[2;4];[];[0;1;8];[]];;
  4. let rec tri_topo1_aux : 'a list list -> 'b list -> 'b list =
  5. fun g l ->
  6. match g with
  7. | [] -> l
  8. | a :: gs -> tri_topo1_aux gs l
  9. ;;
  10. let tri_topological1 : 'a list list -> 'b list =
  11. fun g ->
  12. tri_topo1_aux g [];;
  13. tri_topological1 gex1;;
  14. (*On utilise une fonction auxiliaire pour créer le tri topologique*)
  15. let rec dfs_aux g c i =
  16. match g with
  17. |[] -> c
  18. |t::gs -> if c.(t) = 'B' then dfs_aux gs c i
  19. else if c.(t) = 'G' then dfs_aux gs c i
  20. else dfs_aux gs (dfs_aux t c i) i
  21. ;;
  22. let dfs g =
  23. let c = Array.make (List.length g) 'B' in
  24. dfs_aux g c 0;;
  25. (*utiliser le parcours en profondeur pour créer un tri topologique*)
  26. let tritopologique2 g =
  27. let c = Array.to_list(dfs g) in
  28. let rec aux c i =
  29. match c with
  30. |[] -> []
  31. |c::cs -> if c = 'B' then aux cs (i+1)
  32. else if c = 'G' then aux cs (i+1)
  33. else aux cs (i+1)
  34. in aux c 0;;