Program to check robot can reach target by keep moving on visited spots in Python

Suppose we have a robot that is currently sitting at position (0, 0) on a Cartesian plane. If we have a list of moves containing N(North), S(South), W(West), and E(East), the robot has a special behavior: when it reaches a spot it has visited before, it continues moving in the same direction until it reaches a new unvisited spot. We need to check whether after all its moves, it will end at a target coordinate (x, y).

Start (0,0) (0,1) (0,2) (1,2) (1,3) (0,3) Target (0,-1) Moves: ['N','N','E','N','W','S'] Red dashed line shows continued movement through visited spots

So, if the input is moves = ['N','N','E','N','W','S'] and target coordinate = [0, -1], then the output will be True. The robot moves two steps up, one right, one up again, one left, and one down. Since the current position is already visited, it continues down until reaching an unvisited spot at (0, -1).

Algorithm

To solve this problem, we follow these steps ?

  • Initialize current position: ny := 0, nx := 0

  • Create a set to track visited positions, initially containing (0, 0)

  • For each move in the moves list:

    • Move in the specified direction

    • If the new position is already visited, keep moving in the same direction until reaching an unvisited spot

    • Add the final position to the visited set

  • Return true if the final position matches the target coordinate

Example

class Solution:
    def solve(self, moves, coord):
        ny = nx = 0
        visited = {(0, 0)}
        
        for move in moves:
            if move == "N":
                while (nx, ny) in visited:
                    ny += 1
            elif move == "S":
                while (nx, ny) in visited:
                    ny -= 1
            elif move == "E":
                while (nx, ny) in visited:
                    nx += 1
            else:  # move == "W"
                while (nx, ny) in visited:
                    nx -= 1
            
            visited.add((nx, ny))
        
        return coord[0] == nx and coord[1] == ny

# Test the solution
ob = Solution()
moves = ['N','N','E','N','W','S']
coord = [0, -1]
print(ob.solve(moves, coord))

The output of the above code is ?

True

Step-by-Step Execution

Let's trace through the example to understand how the robot moves ?

def trace_robot_moves(moves, target):
    ny = nx = 0
    visited = {(0, 0)}
    print(f"Start: ({nx}, {ny})")
    
    for i, move in enumerate(moves):
        print(f"Move {i+1}: {move}")
        
        if move == "N":
            while (nx, ny) in visited:
                ny += 1
                print(f"  Moving North to ({nx}, {ny})")
        elif move == "S":
            while (nx, ny) in visited:
                ny -= 1
                print(f"  Moving South to ({nx}, {ny})")
        elif move == "E":
            while (nx, ny) in visited:
                nx += 1
                print(f"  Moving East to ({nx}, {ny})")
        else:  # move == "W"
            while (nx, ny) in visited:
                nx -= 1
                print(f"  Moving West to ({nx}, {ny})")
        
        visited.add((nx, ny))
        print(f"  Final position after move: ({nx}, {ny})")
    
    result = target[0] == nx and target[1] == ny
    print(f"Target: {target}, Final: ({nx}, {ny}), Reached: {result}")
    return result

# Trace the example
moves = ['N','N','E','N','W','S']
target = [0, -1]
trace_robot_moves(moves, target)

The output shows the detailed movement ?

Start: (0, 0)
Move 1: N
  Moving North to (0, 1)
  Final position after move: (0, 1)
Move 2: N
  Moving North to (0, 2)
  Final position after move: (0, 2)
Move 3: E
  Moving East to (1, 2)
  Final position after move: (1, 2)
Move 4: N
  Moving North to (1, 3)
  Final position after move: (1, 3)
Move 5: W
  Moving West to (0, 3)
  Final position after move: (0, 3)
Move 6: S
  Moving South to (0, 2)
  Moving South to (0, 1)
  Moving South to (0, 0)
  Moving South to (0, -1)
  Final position after move: (0, -1)
Target: [0, -1], Final: (0, -1), Reached: True

Key Points

  • The robot keeps track of all visited positions in a set

  • When moving to a previously visited position, it continues in the same direction

  • The algorithm ensures the robot always lands on an unvisited position after each move

  • Time complexity is O(n × m) where n is the number of moves and m is the maximum distance traveled in one direction

Conclusion

This solution simulates a robot that continues moving through visited spots until reaching unvisited territory. The key insight is using a set to track visited positions and implementing the "keep moving" logic with while loops for each direction.

Updated on: 2026-03-25T11:36:09+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements