def freeze(obj):
    """Freeze a state (dict), for memoizing."""
    if isinstance(obj, dict):
        return frozenset({k: freeze(v) for k, v in obj.items()}.items())
    if isinstance(obj, list):
        return tuple([freeze(v) for v in obj])
    return obj