Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- class Point:
- def __init__(self, x, y, connect):
- self.x = x
- self.y = y
- self.connect = connect
- def __str__(self):
- return '({}, {}, {})'.format(self.x, self.y, self.connect)
- def __repr__(self):
- return '({}, {}, {})'.format(self.x, self.y, self.connect)
- def __eq__(self, other):
- return self.x == other.x and self.y == other.y
- def __hash__(self):
- return self.x ** self.y
- def bfs(s, t, graph):
- if s == t:
- return {}
- queue = [s]
- visits = {}
- for i in graph.keys():
- visits[i] = False
- visits[s] = True
- path = { s: -1 }
- while queue:
- v = queue[0]
- queue = queue[1:]
- for u in graph[v]:
- if (not u.connect or visits[u]):
- continue
- visits[u] = True
- queue.append(u)
- path[u] = v
- if u == t:
- return path
- return path
- def get_path(path, s, t):
- arr = [t]
- if not t in path:
- return []
- while t != s:
- arr.append(path[t])
- t = path[t]
- return arr[::-1]
- def delete_node(graph, v):
- for node in graph[v]:
- node.connect = False
- def start(N, M):
- all_nodes = N*M - 2*M
- delete_nodes = 0
- max_x, max_y = [N, M] #or [int(i) for i in input().split()]
- points = []
- for y in range(max_y):
- for x in range(max_x):
- points.append(Point(x, y, True))
- graph = {}
- for point in points:
- graph[point] = []
- if point.x > 0:
- graph[point].append(Point(point.x-1, point.y, True))
- if point.x < max_x - 1:
- graph[point].append(Point(point.x+1, point.y, True))
- if point.y > 0:
- graph[point].append(Point(point.x, point.y-1, True))
- if point.y < max_y - 1:
- graph[point].append(Point(point.x, point.y+1, True))
- p = bfs(Point(0, 0, True), Point(max_x - 1, 0, True), graph)
- path = get_path(p, Point(0, 0, True), Point(max_x - 1, 0, True))
- while p:
- del_node = Point(randint(1, max_x - 2), randint(0, max_y - 1), True)
- check_connectivity = False
- for i in graph[del_node]:
- if i.connect:
- check_connectivity = True
- break
- if check_connectivity:
- delete_nodes += 1
- delete_node(graph, del_node)
- p = bfs(Point(0, 0, True), Point(max_x - 1, 0, True), graph)
- if del_node in path:
- path = get_path(p, Point(0, 0, True), Point(max_x - 1, 0, True))
- if not path:
- #print(del_node)
- return delete_nodes/all_nodes
- #print(path, del_node)
- if __name__ == '__main__':
- count_experiments = 1
- sum_ = 0
- for i in range(count_experiments):
- sum_ += start(20, 10)
- print(sum_/count_experiments)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement