01 Matrix
Explore how to solve the 01 Matrix problem by computing the nearest distance to zero for each cell in a binary matrix. Understand adjacency and constraints while practicing a dynamic programming approach in C++, enhancing your ability to tackle optimization problems efficiently.
We'll cover the following...
Statement
Given an mat, find the distance from each cell to the nearest
Constraints:
mat.row,mat.colmat.row * mat.colmat[i][j]There is at least one
in mat.
Example
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
01 Matrix
Given a matrix, mat = [[0, 0, 0], [0, 1, 0], [1, 0, 0]], find the matrix that contains the distance of the nearest 0 for each cell.
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 1, 0], [1, 0, 0]]
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
[[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
std::vector<std::vector<int>> UpdateMatrix(std::vector<std::vector<int>> mat) {// Replace this placeholder return statement with your codereturn {};}