Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Graph(object):
- def __init__(self, graph_dict=None):
- """ initializes a graph object
- If no dictionary or None is given,
- an empty dictionary will be used
- """
- if graph_dict == None:
- graph_dict = {}
- self.__graph_dict = graph_dict
- def vertices(self):
- """ returns the vertices of a graph """
- return list(self.__graph_dict.keys())
- def edges(self):
- """ returns the edges of a graph """
- return self.__generate_edges()
- def add_vertex(self, vertex):
- """ If the vertex "vertex" is not in
- self.__graph_dict, a key "vertex" with an empty
- list as a value is added to the dictionary.
- Otherwise nothing has to be done.
- """
- if vertex not in self.__graph_dict:
- self.__graph_dict[vertex] = []
- def add_edge(self, edge):
- """ assumes that edge is of type set, tuple or list;
- between two vertices can be multiple edges!
- """
- edge = set(edge)
- (vertex1, vertex2) = tuple(edge)
- if vertex1 in self.__graph_dict:
- self.__graph_dict[vertex1].append(vertex2)
- else:
- self.__graph_dict[vertex1] = [vertex2]
- def __generate_edges(self):
- """ A static method generating the edges of the
- graph "graph". Edges are represented as sets
- with one (a loop back to the vertex) or two
- vertices
- """
- edges = []
- for vertex in self.__graph_dict:
- for neighbour in self.__graph_dict[vertex]:
- if {neighbour, vertex} not in edges:
- edges.append({vertex, neighbour})
- return edges
- def __str__(self):
- res = "vertices: "
- for k in self.__graph_dict:
- res += str(k) + " "
- res += "\nedges: "
- for edge in self.__generate_edges():
- res += str(edge) + " "
- return res
- def find_all_paths(self, start_vertex, end_vertex, path=[]):
- """ find all paths from start_vertex to
- end_vertex in graph """
- graph = self.__graph_dict
- path = path + [start_vertex]
- if start_vertex == end_vertex:
- return [path]
- if start_vertex not in graph:
- return []
- paths = []
- for vertex in graph[start_vertex]:
- if vertex not in path:
- extended_paths = self.find_all_paths(vertex,
- end_vertex,
- path)
- for p in extended_paths:
- paths.append(p)
- return paths
- n, m = map(int, input().split())
- d = {}
- q = {}
- data = []
- string = ""
- for i in range(n):
- s = str(input())
- string += s
- if i > 0:
- for j in range(m - 1):
- d[(i-1) * m + j] = [i * m + j, (i - 1) * m + j + 1]
- d[(i - 1) * m + (m - 1)] = [i * m + (m - 1)]
- for i in range(m - 1):
- d[m * (n - 1) + i] = [m * (n - 1) + i + 1]
- graph = Graph(d)
- path = graph.find_all_paths(0, n * m - 1)
- for i in path:
- s = ''
- for j in i:
- s += string[j]
- bisect.insort(data, s)
- l = int(input())
- print(data[l - 1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement