コード例 #1
0
def link_nodes(num_nodes):
    """
    num_nodes - a list of lists, each list not necessarily of the same length,
    that must be linked.

    Returns a graph with the given nodes linked as per the constraints of the
    problem.
    """
    graph = AdjacencyLists()

    for ri, l in enumerate(num_nodes):
        graph.add_nodes([(ri, ci) for ci, n in enumerate(l)])

    for ri, l in enumerate(num_nodes):
        for ci, n in enumerate(l):
            if (ci + n) < len(l):
                graph.make_neighbor((ri, ci), (ri, ci + n))
            else:
                jumps = ci + n
                _ri, _ci = ri, ci
                
                while jumps != 0 and _ri < len(num_nodes):
                    deductible = jumps - (len(l) - _ci)
                    jumps -= deductible
                    # Because after current row, the column index resets.
                    _ci = 0

                    if jumps < 0:
                        _ci = len(num_nodes[_ri]) + jumps
                        break

                    _ri += 1

                if _ri < len(num_nodes):
                    graph.make_neighbors((ri, ci), (_ri, _ci))
コード例 #2
0
 def test_link_nodes(self):
     easy = [[1, 2]]
     graph = AdjacencyLists()
     graph.add_nodes(((0, 0), (0, 1)))
     graph.make_neighbor((0, 0), (0, 1))
     self.assertEqual(graph, link_nodes(easy))