CISCO Coding Question – Solved

4 Live
Given an n x m grid, where rows are numbered from 7 to n and columns from 1 to m, there are x blocked cells. Their positions are specified by the array blockedPositions[i][] where blockedPositions[i][1] represents the row and blockedPositions[i][2] represents the column position, using 1-based indexing. Starting from the top-left cell (1, 1), the goal is to reach the bottom-right cell (n, m) without visiting any blocked cells. Movement is allowed only up, down, left, or right. The strength of a path is defined as the minimum Manhattan distance from each cell in the path to the nearest blocked cell. To calculate the strength of a specific path, an array minDist[] is created, where minDist[i] represents the minimum distance to any blocked cell for the ith cell visited. The strength of the path is given by min(minDist[]). Among all possible paths from (1, 1) to (n, m), determine the path that maximizes strength. If multiple paths have the same maximum strength, select the one that visits the fewest cells. Return two integers: the maximum strength achievable and the minimum number of cells visited. If it is impossible to navigate from (1, 1) to (n, m), return [-1, -1]. Note: The Manhattan distance between cells (a, b) and (c, d) is defined as abs(a-c) + abs(b-d). Example n=4

Asked in: CISCO

Image of the Question

Question Image Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


from collections import deque

def findOptimalPath(n, m, blockedPositions):
    isBlocked = [[False] * (m + 1) for _ in range(n + 1)]
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To approach this problem, you must understand that it's a variation of a shortest-path problem, but with an added complexity: instead of simply minimizing the number of steps from the starting cell to the goal, you must find a path that **maximizes the minimum Manhattan distance from blocked cells** along the way. Once that maximum possible minimum distance (called the path’s strength) is found, you must also ensure that the selected path uses the fewest number of steps among all paths that achieve that maximum strength.

Let’s break this down into components and gradually construct a logical approach for solving it.

First, consider the environment. You have a grid of size n x m, where some cells are blocked. The goal is to go from cell (1, 1) to cell (n, m) without passing through any blocked cell. The movement is constrained to four directions: up, down, left, and right. From this alone, you can already identify that it is a form of grid traversal — typically solved using BFS (Breadth-First Search) for shortest path problems. However, this problem introduces a new layer — **the concept of “strength”** — that complicates things.

Strength, in this case, refers to the smallest distance from any cell on the path to the closest blocked cell. So, to evaluate any given path, you would need to compute, for every cell on that path, how far it is from the nearest blocked cell, and then take the minimum among those distances. The goal is to maximize that minimum distance — meaning, you're trying to find the safest path, the one that stays as far as possible from blocked cells at its closest point.

To proceed, the first key observation is that this is a **two-layered optimization** problem:
1. **Primary goal**: Maximize the path’s strength.
2. **Secondary goal**: Among all such strongest paths, pick the one with the fewest cells (i.e., shortest path length).

Given these goals, a helpful way to frame the problem is as a **modified shortest-path search** where the priority is not just step count but the path's strength. Here's how you can start thinking about it:

**Step 1: Preprocess the grid to compute distances from blocked cells.**

Before you can even think about the strength of any path, you need a map of how close each cell is to any blocked cell. This is best done with a **multi-source BFS**, where you start from all blocked cells simultaneously and compute the shortest Manhattan distance from each cell in the grid to its nearest blocked cell. The result is a 2D array where each cell holds its minimum distance to a blocked cell. This will serve as your strength reference grid.

**Step 2: Use binary search on strength.**

Once you have the distance map from blocked cells, you can now search for the strongest path from (1,1) to (n,m). Since strength is based on minimum distance to blocked cells, and each cell in the grid already has this value computed, you can treat these distances as a landscape of safety levels.

Now, consider this: to determine if a path of at least strength `k` exists, you can simply **exclude all cells whose distance to blocked cells is less than k**, and then perform a regular BFS from (1,1) to (n,m). If you can reach the destination in this restricted grid, then a path of strength `k` is possible.

Thus, you can perform a **binary search over the possible strength values** (from 0 to the maximum possible distance in the grid) and check whether a valid path exists for each candidate strength. For each strength value `k` that passes this check, you can also store the minimum number of steps it took to reach the goal.

**Step 3: Track the minimum path length for the maximum strength.**

As you perform the binary search and test path feasibility at each strength level, keep track of the highest strength for which a path exists. For each valid strength, also compute the length of the shortest path that maintains that strength level. At the end, you’ll have:
- The maximum strength achievable.
- The length of the shortest path that achieves this strength.

**Edge Case: No valid path exists.**

It’s possible that no path exists from (1,1) to (n,m) without touching blocked cells, or perhaps all paths force the traveler through cells adjacent to blocked positions. You need to account for this by verifying if the BFS ever reaches the target cell. If not, return [-1, -1] to indicate the journey is impossible.

**Summary of your thinking process:**
- Compute the distance of each cell to the nearest blocked cell (multi-source BFS).
- Perform binary search over strength values:
- For each strength candidate, filter the grid to only allow cells with distance ≥ strength.
- Perform BFS to find if (1,1) can reach (n,m) within this filtered grid.
- If yes, record this strength and the path length.
- Continue binary search to find the maximum strength with minimum steps.
- Return the best strength and its corresponding minimum step count.

By decomposing the problem into preprocessing and a binary search over feasible path strengths, you can tackle both layers of optimization in a structured and efficient way.
```


Related Questions