Fewest Clear Cells From Corner to Corner

Quick Overview

Fewest Clear Cells From Corner to Corner. In the square binary grid, travel from (0,0) to (n-1,n-1) using horizontal, vertical or diagonal steps to different neighboring cells.

Fewest Clear Cells From Corner to Corner

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem In the square binary grid, travel from `(0,0)` to `(n-1,n-1)` using horizontal, vertical or diagonal steps to different neighboring cells. Every visited cell must contain 0. Return the minimum number of visited cells, including both endpoints, or -1 if no route exists. ```cpp class Solution { public: int shortestPathBinaryMatrix(vector<vector<int>>& grid); }; ``` ### Examples **Example 1:** ```text Input: grid = [[0]] Output: 1 Explanation: The start already equals the destination and is clear. ``` **Example 2:** ```text Input: grid = [[0,0,1],[1,0,1],[1,0,0]] Output: 3 Explanation: The diagonal route(0,0),(1,1),(2,2) uses3 cells, the minimum for these corners. ``` ### Constraints - The grid has n rows and n columns, with `1 <= n <= 100`. - Every entry is 0 or 1. ### Contract considerations Only 0 cells are traversable, and the grid is square. ```hint Read the boundary condition For a one-cell grid, how should the result distinguish a clear cell from a blocked cell? ``` ### Boundary reminders Only 0 cells are traversable, and the grid is square.

Overview: Fewest Clear Cells From Corner to Corner. In the square binary grid, travel from (0,0) to (n-1,n-1) using horizontal, vertical or diagonal steps to different neighboring cells.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

In the square binary grid, travel from (0,0) to (n-1,n-1) using horizontal, vertical or diagonal steps to different neighboring cells. Every visited cell must contain 0. Return the minimum number of visited cells, including both endpoints, or -1 if no route exists.

class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& grid);
};

Examples

Example 1:

Input: grid = [[0]]
Output: 1
Explanation: The start already equals the destination and is clear.

Example 2:

Input: grid = [[0,0,1],[1,0,1],[1,0,0]]
Output: 3
Explanation: The diagonal route(0,0),(1,1),(2,2) uses3 cells, the minimum for these corners.

Constraints

  • The grid has n rows and n columns, with 1 <= n <= 100 .
  • Every entry is 0 or 1.

Contract considerations

Only 0 cells are traversable, and the grid is square.

Boundary reminders

Only 0 cells are traversable, and the grid is square.