total
matrix with the same dimensions as grid
to store the sum of distances from houses to empty lands.emptyLandValue
to 0 and minDist
to INT_MAX
.grid
, if it is a house (value equals 1), start a BFS:
emptyLandValue
, update the total
matrix with the distance and decrement the cell's value by 1.emptyLandValue
by 1.total
matrix to find the minimum distance for cells with housesReached
equal to the total number of houses.minDist
is still INT_MAX
, return -1
. Otherwise, return minDist
.