To address the issue of non-termination in BFS when the target is unreachable, we can augment the algorithm with cycle detection and pruning strategies to bound the search space. Here's an improved approach:
Enhanced Approach: BFS with State Pruning
-
Cycle Detection:
- Use a
visited set to avoid revisiting states. This prevents infinite loops caused by cycles in the state graph.
-
Pruning Strategies:
- Component-wise Bounds: If all vectors in the set are non-negative, states where any component exceeds the target's corresponding component can be pruned (since further additions will only increase components).
- Depth Limit: Impose a maximum search depth (e.g., based on the Manhattan distance between
s and t).
Modified Code with Termination
from collections import deque
def find_sequence(vectors, s, t, max_depth=1000):
if s == t:
return []
d = len(s)
start = tuple(s)
target = tuple(t)
# Check if target is unreachable due to component-wise constraints
if any(t[i] < s[i] for i in range(d)):
# If any vector can decrease components, proceed; else, prune
if all(all(v[i] >= 0 for v in vectors) for i in range(d)):
return None # No way to decrease components
queue = deque([(start, [])])
visited = set()
visited.add(start)
depth = 0
while queue and depth < max_depth:
level_size = len(queue)
for _ in range(level_size):
current_state, path = queue.popleft()
current_tuple = tuple(current_state)
for v in vectors:
next_state = tuple(current_state[i] + v[i] for i in range(d))
if next_state == target:
return path + [v]
if next_state not in visited and all(x >= 0 for x in next_state):
visited.add(next_state)
queue.append((next_state, path + [v]))
depth += 1
return None # Target unreachable within max_depth
# Example usage:
# vectors = [(1, 0), (0, 1)]
# s = (1, 1)
# t = (3, 2)
# print(find_sequence(vectors, s, t)) # Output: [(1, 0), (1, 0), (0, 1)]
Key Improvements
-
Cycle Prevention:
- The
visited set ensures states are not re-explored, avoiding infinite loops.
-
Component-wise Pruning: