479. Return a Cleaning Robot to Its Charger
Return a Cleaning Robot to Its Charger

A cleaning robot must return to its charger on a rectangular office floor. Cells may be blocked by furniture.

The robot is initially stopped. Each command sends it up, down, left, or right until its next step would enter a blocked cell or leave the floor. It stops in the last free cell and can then receive another command. It cannot stop or turn earlier.

The charger does not stop the robot automatically. The robot must stop exactly on the charger; passing over it does not count.

Method Signature

boolean canReachCharger(List<String> floorPlan, List<Integer> robotCell, List<Integer> chargerCell)
  • floorPlan: rows from top to bottom. Each string contains comma-separated cells, where 0 means free and 1 means blocked. For example, "0,1,0" describes three cells.
  • robotCell: the starting position as [row, column], using zero-based indices.
  • chargerCell: the charger position in the same coordinate format.
  • Return true if some sequence of commands lets the robot stop on the charger; otherwise, return false.

Example calls label arguments for readability.

Constraints

  • 1 ≤ floorPlan.size() ≤ 100.
  • Each row contains between 1 and 100 cells, and all rows contain the same number of cells.
  • Row strings contain only 0 and 1 separated by commas, without spaces.
  • robotCell.size() = chargerCell.size() = 2.
  • Both positions are within the floor, identify free cells, and are different.
  • There are at least two free cells.

Examples

Example 1

canReachCharger(
floorPlan = ["0,1,0,0,0", "0,1,0,1,0", "0,0,0,1,0"],
robotCell = [0, 0],
chargerCell = [0, 4])

Output: true

Explanation: Commands down, right, up, and right stop the robot at [2, 0], [2, 2], [0, 2], and finally the charger at [0, 4].

Example 2

canReachCharger(
floorPlan = ["0,0,0,0,0"],
robotCell = [0, 4],
chargerCell = [0, 2])

Output: false

Explanation: The robot can stop only at either end of this row. Moving left passes over the charger and stops at [0, 0].

Example 3

canReachCharger(
floorPlan = ["0,0,0", "1,1,1", "0,0,0"],
robotCell = [0, 1],
chargerCell = [2, 2])

Output: false

Explanation: The blocked middle row separates the robot from the charger.



Please use Laptop/Desktop or any other large screen to add/edit code.