Advertisement
Guest User

Problema_das_Chaves

a guest
May 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. class Graph:
  5.     def __init__(self, vert):
  6.         self.vert = vert
  7.         self.graph = [[0] * vert for i in range(vert)]
  8.         self.key_location = random.randint(0, vert-1)
  9.         self.visited = [False for i in range(vert)]
  10.         self.comodos = {0: "Sala",
  11.                         1: "Cozinha",
  12.                         2: "Corredor",
  13.                         3: "Banheiro",
  14.                         4: "Quarto de casal",
  15.                         5: "Quarto de visita"}
  16.  
  17.     def show_graph(self):
  18.         col, row = 65, 65
  19.         for i in range(self.vert):
  20.             for j in range(self.vert):
  21.                 print("{}\t".format(self.graph[i][j]), end="")
  22.             print("\033[1;31m{}\033[m".format(chr(row)))
  23.             row += 1
  24.         for j in range(self.vert):
  25.             print("\033[1;31m{}\033[m\t".format(chr(col)), end="")
  26.             col += 1
  27.         print("")
  28.  
  29.     def add_edge(self, vert1, vert2):
  30.         if self.graph[vert1][vert2] != 1 and self.graph[vert2][vert1] != 1:
  31.             self.graph[vert1][vert2] = 1
  32.             self.graph[vert2][vert1] = 1
  33.         else:
  34.             return
  35.  
  36.     def search_key(self, start):
  37.         # Este algoritmo está usando busca por profundidade (implícito: recursão)
  38.         local = start
  39.         self.visited[local] = True
  40.         if local == self.key_location:
  41.             print("\nChave encontrada! Local: {}.".format(self.comodos[local]))
  42.             return self.key_location
  43.         else:
  44.             for i in range(self.vert):
  45.                 if self.graph[local][i] == 1 and self.visited[i] is False and i != local:
  46.                     self.search_key(i)
  47.  
  48.  
  49. g = Graph(6)
  50. g.add_edge(0, 1)
  51. g.add_edge(0, 2)
  52. g.add_edge(2, 4)
  53. g.add_edge(2, 5)
  54. g.add_edge(4, 3)
  55. g.show_graph()
  56. g.search_key(0)
  57.  
  58. SAÍDA:
  59.  
  60. C:\Users\Oraplas_AutoCard\PycharmProjects\Algoritmos_de_busca\venv\Scripts\python.exe C:/Users/Oraplas_AutoCard/PycharmProjects/Algoritmos_de_busca/Problema_das_chaves.py
  61. 0   1   1   0   0   0   A
  62. 1   0   0   0   0   0   B
  63. 1   0   0   0   1   1   C
  64. 0   0   0   0   1   0   D
  65. 0   0   1   1   0   0   E
  66. 0   0   1   0   0   0   F
  67. A   B   C   D   E   F  
  68.  
  69. Chave encontrada! Local: Cozinha.
  70.  
  71. Process finished with exit code 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement