Grid Exploration
Problem statement
You are given a rectangular grid. Each character is - for an open cell or x for an obstacle.
Start at the unblocked cell (row_start, column_start) and reach the unblocked cell (row_end, column_end). All coordinates use zero-based row and column indices.
Each move travels one cell up, down, left, or right, stays inside the grid, and enters an open cell. Moving down or right costs 0; moving up or left costs 1. Cells may be revisited, and each move is charged according to its direction.
Return the minimum total cost. Return -1 if the target is unreachable. If the endpoints are identical, return 0.
Function
exploreGrid(grid: String[], row_start: int, column_start: int, row_end: int, column_end: int) → intExamples
Example 1
grid = ["-----","---x-","--x-x","-----"]row_start = 2column_start = 3row_end = 1column_end = 4return = 5Move down to (3,3), left twice to (3,1), up three times to (0,1), right three times to (0,4), then down to (1,4). Only the two left and three up steps are charged, for a total of 5.
Example 2
grid = ["---","---"]row_start = 0column_start = 0row_end = 1column_end = 2return = 0A route using only down and right reaches the target at zero cost.
Example 3
grid = ["---","---"]row_start = 1column_start = 2row_end = 0column_end = 0return = 3Any route needs at least one up step and two left steps. A direct route has cost 3.
Example 4
grid = ["-x--","-xx-","----","-x-x","-xx-"]row_start = 3column_start = 0row_end = 0column_end = 2return = 4Go up once, right three times along row 2, up twice along column 3, then left once to (0,2). The three up steps and one left step cost 4.
Example 5
grid = ["-x-","-xx","---"]row_start = 2column_start = 0row_end = 0column_end = 2return = -1The destination (0,2) has blocked neighbors and cannot be reached.
Constraints
1 <= n, m <= 1500, wherenis the number of rows andmis the length of each row.- Every row has the same length.
- Every character is
-orx. 0 <= row_start, row_end < n0 <= column_start, column_end < m- The starting and target cells are unblocked.