def main(): with open(sys.argv[1]) as f: lines = f.read().splitlines() adj = [] for line in lines: row = [] for node in line.split(','): if node == '-': row.append(None) else: row.append(int(node)) adj.append(row) num_nodes = len(adj) # make sure the adjacency matrix is square assert all(len(row) == num_nodes for row in adj) graph = WeightedGraph() for i in range(num_nodes): graph.add_node(i) for x, row in enumerate(adj): for y, weight in enumerate(row): if weight is not None: graph.add_arc(x, y, weight) mst = min_spanning_tree(graph) # Now we want to consider half of the adjacency matrix, so we can # sum the total weight of all arcs. half_adj = [] for i, row in enumerate(adj): new_row = [] for j, weight in enumerate(row): if i <= j: new_row.append(weight) else: new_row.append(None) half_adj.append(new_row) # Now remove all of the arcs in the mst, so the arcs we are left # with are the ones that we are able to remove. for mst_arc_source, mst_arc_target in mst: half_adj[mst_arc_source][mst_arc_target] = None half_adj[mst_arc_target][mst_arc_source] = None print(sum(sum(filter(None, row)) for row in half_adj))
def main(): global matrix with open(sys.argv[1]) as f: lines = f.readlines() matrix = [[int(n) for n in l.strip().split(',')] for l in lines] """ matrix = [[131, 673, 234, 103, 18], [201, 96, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 37, 331]] """ matrix_size = len(matrix) # the cost of arriving at each node is the value at that node g = WeightedGraph() for lnum, line in enumerate(matrix): for cnum, value in enumerate(line): g.add_node((lnum, cnum)) # from below if (0 <= lnum + 1 < matrix_size): g.add_arc((lnum + 1, cnum), (lnum, cnum), value) # from above if (0 <= lnum - 1 < matrix_size): g.add_arc((lnum - 1, cnum), (lnum, cnum), value) # from right if (0 <= cnum + 1 < matrix_size): g.add_arc((lnum, cnum + 1), (lnum, cnum), value) # from left if (0 <= cnum - 1 < matrix_size): g.add_arc((lnum, cnum - 1), (lnum, cnum), value) route, cost = a_star(g, (0, 0), (matrix_size - 1, matrix_size - 1)) print(cost + matrix[0][0])