graphes.ml 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. type graphe = int list array;;
  2. let rec parcours_dfs_aux (g:graphe) (listevue:int list) (listeavoir:int list):unit = match listeavoir with
  3. | [] -> ()
  4. | t::q -> if (List.mem t listevue) then parcours_dfs_aux g listevue q
  5. else
  6. begin
  7. parcours_dfs_aux g (t::listevue) (g.(t)@q)
  8. end;;
  9. let parcours_profondeur (g:graphe) (sommet:int):unit = parcours_dfs_aux g [] [sommet];;
  10. let rec bfs_aux (g:graphe) (listevue:int list) (listeavoir:int list):int list = match listeavoir with
  11. | [] -> listevue
  12. | t::q -> if (List.mem t listevue) then bfs_aux g listevue q
  13. else
  14. begin
  15. bfs_aux g (t::listevue) (q@g.(t))
  16. end;;
  17. let connexe g = let parcours = bfs_aux g [] [0] in
  18. if (List.length parcours = List.length g) then true
  19. else false;;
  20. let composantes_connexes g = let n = Array.length g in
  21. let cc = Array.make n 0 in
  22. for s = 0 to n-1 do
  23. if (cc.(s) = 0) then
  24. begin
  25. let parcours = bfs_aux g [] [s] in
  26. List.iter (fun x -> cc.(x) <- s+1) parcours
  27. end
  28. done;
  29. cc;;