Connect

You are given a square grid consisting of '0's (land) and '1's (water). You start at a land cell (r1, c1) and want to travel to a target land cell (r2, c2). You can only move up, down, left, or right, and you can only walk on land cells.

If the target cell is currently unreachable, you can build at most one tunnel connecting any two land cells (rs, cs) and (rt, ct). The cost of building this tunnel is calculated as (rs - rt)2 + (ct - ct)2.

Find the minimum cost to make the target cell reachable from the start cell. Return 0 if it is already reachable. (Note: Input coordinates are 1-indexed).

Example 1:

Input: (r1, c1) = (1, 1), (r2, c2) = (5, 5), grid = [ ["0","0","0","0","1"],

["1","1","1","1","1"],

["0","0","1","1","1"],

["0","0","1","1","0"],

["0","0","1","1","0"]

]

Output:10

Explanation:

From (1, 1), you can walk to all 0s in the first row, reaching (1, 4). From (5, 5), you can walk to the adjacent 0s, reaching (4, 5). Connect (1, 4) to (4, 5) for a cost of (1 - 4)2 + (4 - 5)2 = 10

Example 2:

Input: (r1, c1) = (1, 3) (r2, c2) = (3, 1), grid =[

["0","1","0"],

["1","0","1"],

["0","1","0"]

]

Output: 8

Explanation:

Both the start at (1, 3) and the target at (3, 1) are completely isolated by water. Connect (1, 3) directly to (3, 1). The cost is (1 - 3)2 + (3 - 1)2 = 8.

Now Your Turn!

Pick the correct output for the given input

Input: (r1, c1) = (1, 1), (r2, c2) = (1, 3) , grid = [

["0","1","0"],

["1","1","1"],

["0","0","0"]

]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= grid.length == grid[0].length <= 50
  • 1 <= r1, c1, r2, c2 <= grid.length
  • grid contains only '0' and '1', and both the start and target cells are guaranteed to be '0'.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minTunnelCost(int r1, int c1, int r2, int c2, vector<vector<char>>& grid) {
}
};
Test Case

Input:

C1
C2
Grid
R1
R2