Week 07
2025-05-21
Lecture
Practice
Slide Set Introduction to graphs Slide Set Drawing graphs in python
graph = { 'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C'] }
import numpy as np nodes = ['A', 'B', 'C', 'D'] adj_matrix = np.array([ [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0] ]) print(adj_matrix)
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'D')]) nx.draw(G, with_labels=True) plt.show()
from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) while queue: vertex = queue.popleft() if vertex not in visited: print(vertex) visited.add(vertex) queue.extend(set(graph[vertex]) - visited) bfs(graph, 'A')
import networkx as nx G = nx.Graph() G.add_weighted_edges_from([('A', 'B', 1), ('A', 'C', 2), ('B', 'C', 1), ('B', 'D', 5), ('C', 'D', 3)]) path = nx.shortest_path(G, source='A', target='D', weight='weight') print("Shortest path from A to D:", path)