9.6 KiB
9.6 KiB
In [ ]:
import networkx as nx
import matplotlib.pyplot as plt
# Création du graphe
G = nx.Graph()
G.add_edges_from([
('Alice', 'Bob'), ('Alice', 'Emma'),
('Bob', 'Chloé'), ('Bob', 'Félix'),
('Chloé', 'David'), ('Chloé', 'Gaël')
])
pos = nx.spring_layout(G, seed=0)
plt.figure(figsize=(6,4))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1000)
plt.title('Réseau social — Diffusion de la nouvelle')
plt.show()In [ ]:
source = 'Alice'
T = nx.bfs_tree(G, source=source)
plt.figure(figsize=(6,4))
nx.draw(T, with_labels=True, node_color='lightgreen', node_size=1000)
plt.title(f'Arbre BFS à partir de {source}')
plt.show()
print('Ordre du parcours BFS :')
print(list(nx.bfs_edges(G, source)))
distances = nx.single_source_shortest_path_length(G, source)
print('\nDistances sociales depuis Alice :')
for k, v in distances.items():
print(f'{k} : {v}')In [ ]:
source2 = 'Chloé'
T2 = nx.bfs_tree(G, source=source2)
plt.figure(figsize=(6,4))
nx.draw(T2, with_labels=True, node_color='lightcoral', node_size=1000)
plt.title(f'Arbre BFS à partir de {source2}')
plt.show()
print('Distances sociales depuis Chloé :')
for k, v in nx.single_source_shortest_path_length(G, source2).items():
print(f'{k} : {v}')In [ ]:
# Ajout d'une personne isolée
G.add_node('Hugo')
plt.figure(figsize=(6,4))
pos = nx.spring_layout(G, seed=1)
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1000)
plt.title('Réseau social avec une personne isolée (Hugo)')
plt.show()
print('Composantes connexes du graphe :')
for i, comp in enumerate(nx.connected_components(G)):
print(f'Composante {i+1} : {comp}')