Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Vertex:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def __eq__(self, other):
- return self.x == other.x and self.y == other.y
- def __ne__(self, other):
- return self.x != other.x or self.y != other.y
- def __lt__(self, other):
- if self.x == other.x:
- return self.y < other.y
- else:
- return self.x < other.x
- def __hash__(self):
- return hash(str(self.x) + str(self.y))
- def __str__(self):
- return str(self.x) + " " + str(self.y)
- height, width = 0, 0
- field = []
- graph, shortest_way = dict(), dict()
- def file_input(filename):
- global field, height, width
- with open(filename, "r") as inp:
- lines = inp.readlines()
- for line in lines:
- field.append(line.split())
- height, width = len(field), len(field[0])
- def check(x, y):
- global field, width, height
- if (1 <= x <= width) and (1 <= y <= height):
- return field[x][y] == '1'
- else:
- return False
- def create_graph():
- global field, graph, width, height
- for i in range(1, height):
- for j in range(1, width):
- if field[i][j] == '1':
- v = Vertex(i, j)
- graph[v] = []
- shortest_way[v] = {}
- if check(i + 1, j):
- graph[v].append(Vertex(i + 1, j))
- if check(i, j + 1):
- graph[v].append(Vertex(i, j + 1))
- if check(i, j - 1):
- graph[v].append(Vertex(i, j - 1))
- if check(i - 1, j):
- graph[v].append(Vertex(i - 1, j))
- if i == 2 and j == 1:
- uuu = Vertex(2, 1)
- def bfs(st):
- global graph, shortest_way
- queue = []
- used = {st: True}
- for u in graph[st]:
- shortest_way[st][u] = u
- queue.append(u)
- used[u] = True
- while len(queue) > 0:
- v = queue[0]
- queue.remove(queue[0])
- for u in graph[v]:
- if not used.get(u, False):
- queue.append(u)
- shortest_way[st][u] = shortest_way[st][v]
- used[u] = True
- def main(filename):
- file_input(filename)
- create_graph()
- for vertex in graph:
- bfs(vertex)
- # main("input.txt")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement