Program to find out is a point is reachable from the current position through given points in Python

In a 2D space, we have a pointer at position (px, py) that needs to move to destination (qx, qy). The pointer can only move to adjacent cells: (x+1, y), (x-1, y), (x, y+1), or (x, y-1). We're given an array of paths containing intermediate points that must be processed serially. We need to find the minimum number of path points required to reach the destination, or return -1 if unreachable.

Problem Example

If we have px = 1, py = 1, qx = 2, qy = 3, paths = [[1, 2], [0, 1], [0, 2], [1, 3], [3, 3]], the output will be 4.

Processing points serially ?

  • Point (1, 2): Move made, current position (1, 2). Points traversed: 1
  • Point (0, 1): No move possible, position stays (1, 2). Points traversed: 2
  • Point (0, 2): No move possible, position stays (1, 2). Points traversed: 3
  • Point (1, 3): Move made, current position (1, 3). Points traversed: 4

From (1, 3), we can reach destination (2, 3) in one step, so the answer is 4.

Algorithm Approach

We use binary search combined with BFS (Breadth-First Search) to find the minimum number of path points needed ?

  1. Create a helper function that checks if destination is reachable using first k path points
  2. Use binary search to find the minimum k where destination becomes reachable
  3. BFS explores all possible moves from current position through available vertices

Implementation

from collections import deque

def solve(px, py, qx, qy, paths):
    def helper(k):
        # Create set of available vertices including start and end points
        vertices = {(px, py), (qx, qy)}
        
        # Add first k path points to available vertices
        for x, y in paths[:k]:
            vertices.add((x, y))
        
        # BFS to check if destination is reachable
        queue = deque([(px, py)])
        
        while queue:
            x, y = queue.popleft()
            
            # Check if we reached destination
            if (x, y) == (qx, qy):
                return True
            
            # Explore all 4 adjacent directions
            for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                next_x, next_y = x + dx, y + dy
                
                if (next_x, next_y) in vertices:
                    queue.append((next_x, next_y))
                    vertices.remove((next_x, next_y))  # Mark as visited
        
        return False
    
    # Binary search for minimum k
    left, right = -1, len(paths) + 1
    
    while left + 1 < right:
        mid = left + (right - left) // 2
        
        if helper(mid):
            right = mid
        else:
            left = mid
    
    return right if right <= len(paths) else -1

# Test the function
result = solve(1, 1, 2, 3, [[1, 2], [0, 1], [0, 2], [1, 3], [3, 3]])
print(f"Minimum path points needed: {result}")
Minimum path points needed: 4

How It Works

The algorithm uses binary search on the number of path points and BFS for reachability testing ?

  1. Binary Search: Tests different values of k to find minimum path points needed
  2. Helper Function: Creates a graph with start, end, and first k path points
  3. BFS Traversal: Explores all reachable positions from the starting point
  4. Adjacency Check: Only allows moves to horizontally or vertically adjacent cells

Time Complexity

Operation Complexity Explanation
Binary Search O(log n) Search space is path array length
BFS per iteration O(k) k vertices in worst case
Overall O(n log n) n is length of paths array

Conclusion

This solution efficiently finds the minimum path points needed using binary search and BFS. The algorithm handles the constraint that path points must be processed serially while allowing flexible movement between adjacent cells.

Updated on: 2026-03-26T16:54:21+05:30

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements