Created
November 10, 2022 15:24
-
-
Save drmcarvalho/799484b0e4d21ade20ab8e812cda2cac to your computer and use it in GitHub Desktop.
Grafo busca em amplitude e profundidade
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Algoritmos de busca em grafos escolhidos para o projeto.""" | |
class BuscaEmProfundidade(object): | |
def algoritmo(self, grafo, inicio, objetivo): | |
def buscaprofundidade(grafo, inicio, objetivo): | |
pilha = [(inicio, [inicio])] | |
while pilha: | |
(vertice, caminho) = pilha.pop() | |
for next in grafo[vertice] - set(caminho): | |
if next == objetivo: | |
yield caminho + [next] | |
else: | |
pilha.append((next, caminho + [next])) | |
try: | |
return next(buscaprofundidade(grafo, inicio, objetivo)) | |
except StopIteration: | |
return None | |
class BuscaEmAmplitude(object): | |
def algoritmo(self, grafo, inicio, objetivo): | |
def buscaamplitude(grafo, inicio, objetivo): | |
fila = [(inicio, [inicio])] | |
while fila: | |
(vertice, caminho) = fila.pop(0) | |
for next in grafo[vertice] - set(caminho): | |
if next == objetivo: | |
yield caminho + [next] | |
else: | |
fila.append((next, caminho + [next])) | |
try: | |
return next(buscaamplitude(grafo=grafo, inicio=inicio, objetivo=objetivo)) | |
except StopIteration: | |
return None | |
class Busca(object): | |
def __init__(self, grafo=None, inicio=None, objetivo=None): | |
if grafo is None or inicio is None or objetivo is None: | |
raise Exception('Verifique se os parametros foram informados corretamente.') | |
self.grafo = grafo | |
self.inicio = inicio | |
self.objetivo = objetivo | |
def profundidade(self): | |
profundidade = BuscaEmProfundidade() | |
return profundidade.algoritmo(grafo=self.grafo, inicio=self.inicio, objetivo=self.objetivo) | |
def amplitude(self): | |
amplitude = BuscaEmAmplitude() | |
return amplitude.algoritmo(grafo=self.grafo, inicio=self.inicio, objetivo=self.objetivo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment