Skip to content

Algoritmos Agregados #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions mpi4py_examples/JRRS_CEAY_GYPB/bfs_dfs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from collections import defaultdict, deque
import time


class GraphAlgorithms:
"""
Clase para implementar algoritmos de búsqueda en grafos.
"""

def __init__(self) -> None:
"""
Inicializa un grafo vacío.
"""
self.graph: defaultdict[list[int]] = defaultdict(list)

def add_edge(self, u: int, v: int) -> None:
"""
Agrega una arista entre los nodos u y v.

Parámetros:
u (int): Nodo de inicio de la arista.
v (int): Nodo de fin de la arista.
"""
self.graph[u].append(v)

def dfs_method(self, start_node: int) -> None:
"""
Realiza un recorrido DFS (Depth First Search) en el grafo.

Parámetros:
start_node (int): Nodo de inicio del recorrido DFS.
"""
visited: set[int] = set()

def dfs_util(node: int) -> None:
visited.add(node)
print(node, end=" ")

for neighbor in self.graph[node]:
if neighbor not in visited:
dfs_util(neighbor)

start_time: float = time.time()
dfs_util(start_node)
end_time: float = time.time()
print("\nTiempo de ejecución del DFS:", end_time - start_time,
"segundos")

def bfs_method(self, start_node: int) -> None:
"""
Realiza un recorrido BFS (Breadth First Search) en el grafo.

Parámetros:
start_node (int): Nodo de inicio del recorrido BFS.
"""
visited: set[int] = set()
queue: deque[int] = deque([start_node])
visited.add(start_node)

start_time: float = time.time()

while queue:
node: int = queue.popleft()
print(node, end=" ")

for neighbor in self.graph[node]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)

end_time: float = time.time()
print("\nTiempo de ejecución del BFS:", end_time - start_time,
"segundos")


# Ejemplo de uso
if __name__ == "__main__":
graph = GraphAlgorithms()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)

print("Recorrido DFS comenzando desde el nodo 2:")
graph.dfs_method(2)

print("\nRecorrido BFS comenzando desde el nodo 2:")
graph.bfs_method(2)