BFS: DFS:: Analysis of Breadth First and Depth First Search in Terms of Time and Space
BFS: DFS:: Analysis of Breadth First and Depth First Search in Terms of Time and Space
Analysis of Breadth First and Depth First Search in Terms of Time and Space end_ me = me. me()
graph = { graph = { from collec ons import defaultdict import me execu on_ me = end_ me - start_ me
'5' : ['3','7'], '5' : ['3','7'], import sys class memory_usage = sys.getsizeof(graph)
'3' : ['2', '4'], '3' : ['2', '4'], Graph: return execu on_ me, memory_usage
'7' : ['8'], '7' : ['8'], def init (self): if name == " main ":
'2' : [], '2' : [], self.graph = defaultdict(list) g = Graph() g.add_edge(0, 1)
'4' : ['8'], '4' : ['8'], def add_edge(self, u, v): g.add_edge(0, 2)
'8' : [] '8' : [] self.graph[u].append(v) g.add_edge(1, 2)
} } def bfs(self, start): g.add_edge(2, 0)
visited = [] visited = set() visited = set() g.add_edge(2, 3)
queue = [] def dfs(visited, graph, node): queue = [start] g.add_edge(3, 3)
def bfs(visited, graph, node): if node not in visited: print (node) visited.add(node) visited.add(start) start_node = 2
visited.apped(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) while queue: bfs_ me, bfs_memory = analyze_algorithm(g.bfs, g.graph, start_node)
queue.append(node) print ("Following is the Depth-First Search") vertex = queue.pop(0) dfs_ me, dfs_memory = analyze_algorithm(g.dfs, g.graph, start_node)
while queue: dfs(visited, graph, '5') for neighbor in self.graph[vertex]: print("BFS Execu on Time:", bfs_ me)
m = queue.pop(0) if neighbor not in visited: print("BFS Memory Usage:", bfs_memory)
print (m, end = " ") queue.append(neighbor) visited.add(neighbor) print("DFS Execu on Time:", dfs_ me)
for neighbour in graph[m]: def dfs_u l(self, vertex, visited): visited.add(vertex) print("DFS Memory Usage:", dfs_memory)
if neighbour not in visited: for neighbor in self.graph[vertex]: if neighbor not in visited:
visited.append(neighbour) self.dfs_u l(neighbor, visited) def dfs(self, start):
queue.append(neighbour) visited = set() self.dfs_u l(start, visited)
print ("Following is the Breadth-First Search") def analyze_algorithm(algorithm, graph, start_node):
bfs(visited, graph, '5') start_ me = me. me()
algorithm(graph, start_node)
return new_centroids
np.random.seed(0)
X, _ = np.random.randn(100, 2), None kmeans = KMeans(n_clusters=3)
labels = kmeans.fit(X)
plt.figure(figsize=(8, 6))
plt.sca er(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.sca er(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='x', c='red',
s=100, label='Centroids')
plt. tle('K-means Clustering') plt.xlabel('Feature 1')
plt.ylabel('Feature 2') plt.legend()
plt.show()