Compute Every Binary Cell Distance to a Zero

Quick Overview

Compute Every Binary Cell Distance to a Zero. Return a matrix whose entry at each cell is its shortest distance to any zero in mat.

Compute Every Binary Cell Distance to a Zero

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Return a matrix whose entry at each cell is its shortest distance to any zero in mat. Moving to a cell sharing an edge costs one; diagonal moves are not allowed. At least one zero exists. ```cpp class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& mat); }; ``` ### Examples **Example 1:** ```text mat = [[1,1,0]] Output: [[2,1,0]] Explanation: Distances increase along the row away from the zero. ``` **Example 2:** ```text mat = [[0,1],[1,1]] Output: [[0,1],[1,2]] Explanation: The lower-right cell needs two edge moves. ``` ### Constraints - Rectangular m-by-n input: m and n are each in 1..10000, and total cells m*n is in 1..10000. Entries are binary, with at least one zero. ### Clarifying Questions Start from all zeros and count only edge-adjacent moves. ```hint Read the boundary condition Can all zeros act as simultaneous search sources? ``` ### Contract considerations Start from all zeros and count only edge-adjacent moves.

Overview: Compute Every Binary Cell Distance to a Zero. Return a matrix whose entry at each cell is its shortest distance to any zero in mat.

Amazon logo
Amazon
Sep 14, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return a matrix whose entry at each cell is its shortest distance to any zero in mat. Moving to a cell sharing an edge costs one; diagonal moves are not allowed. At least one zero exists.

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat);
};

Examples

Example 1:

mat = [[1,1,0]]
Output: [[2,1,0]]
Explanation: Distances increase along the row away from the zero.

Example 2:

mat = [[0,1],[1,1]]
Output: [[0,1],[1,2]]
Explanation: The lower-right cell needs two edge moves.

Constraints

  • Rectangular m-by-n input: m and n are each in 1..10000, and total cells m*n is in 1..10000. Entries are binary, with at least one zero.

Clarifying Questions Guidance

Start from all zeros and count only edge-adjacent moves.

Contract considerations

Start from all zeros and count only edge-adjacent moves.