Thursday, August 17th
Matrix distances
Given a binary matrix, find the distances of non-zero cells to zero cells
Finding distances to and from groups of cell nodes brings to mind breadth-first search
We will create a solution matrix and a queue. Then for each cell with a 0 in the original array, we mark its distance as zero in the solution matrix, and push the cell coordinates onto the queue. Then, we will iterate through the queue, and for each cell, find untraversed neighbors, update the neighbor's distance in the solution matrix, and push the neighbor to the back of the queue. This continues until the queue is empty, when all shortest distances have been entered in the solution matrix
Start with variable initialization
Then iterate through the input matrix, and for each 0 cell in the input matrix, mark its distance to zero in the solution matrix as 0. Also push each 0 cell onto the queue, and increment the size variable, which tracks the size of the queue.
The size variable will allow us to iterate through the queue for all nodes of the same distance
Next, iterate through nodes pushed onto the queue. We initialize the variable distance to 1, since the first iteration through the queue will find cells of distance 1 from the 0 cells. For each entry in the queue, we extract the row and column index
With the row and column, we check immediate neighbors to see if they've been visited yet, minding boundary conditions. If not, we update the cell's distance in the answer matrix, and push the neighbor's coordinates onto the queue
After all cells of a given depth have been explored, we update size to the size the queue, and increment distance by 1. The size variable allows us to only use one queue/data structure for storing cells.
Finally, return the answer matrix
Fairly straight forward breadth-first search problem. The Editorial also had a dynamic programming approach where you make a pass from top-left to bottom-right, then bottom-right to top-left, marking shortest paths along the way
Full code of my breadth first search solution below. A bit long, but all makes sense
_(cropped).jpg)
Comments
Post a Comment