317 Shortest Distance from All Buildings
Accepted (attempt 2):
The Idea: First collect all the houses within the matrix. Then for each house, BFS on it with the 4 cardinal directions. Additionally, only accept areas that are empty (0). Along the way, output the distances collected onto another matrix, and ensure that the area you step into isn't stepped into again using an additional matrix. Additionally in the BFS, if a house is uncovered, mark it as visited, and remove the house from the collection of houses. Once the BFS algorithm terminates, all the houses should be visited, or in other words, the set that contains all houses should be empty. If not, the matrix is not valid and return -1. Additionally, we may come across a matrix that is valid, but contains blocked off areas only some houses can get to. This this would provide an unfair advantage we collect all the unexplored areas (0's) at the end of the BFS. These areas indicate blocked of areas in the matrix from the perspective of the current house getting BFS'ed on. For these areas, I simply marked them as as obstacle, so that the algorithm I will describe next ignores them. Next, we collect all the BFS'ed matricies, and stack them together into a tensor. Finally, we accumulate the weights of each [i][j][0...k] matrix (where k is the number of houses), and return the minimum result.
Complexity: O(N) space and O(N^2) time where N is the number of elements in matrix.
Testing
Timed Out Implementation (attempt 1):
The approach I took was to run BFS on all valid cells in the grid. BFS works in this case of finding the shortest path, because the 'edge lengths' from cell-to-cell are all the same (0). Each run, I would first ensure that it is an empty cell, then grab the total distance accumulated in the BFS algorithm. As I go, i optimize for the minimum distance found. I also make sure to check for a few things:
Visited cells. I maintain a boolean matrix that ensures that I don't repeat going back into a cell (as their obvious cycles).
Houses. I do a quick iterative search for all the houses in the grid matrix, and store them as pairs. They will be used to confirm that at the end of the BFS search algorithm that all houses where explored. If not, I return a max integer as an indicator that the algorithm failed in that regard.
Bounds: I cannot exceed the size of the grid, neither can I enter obstacles (==2).
In the BFS algorithm I maintain a queue that keeps track of the previous level. This will ensure that the next level I enqueue is just 1 above it. I also make sure that if the current cell is on a house, I cannot enqueue the next element (as it is not possible to move from one house to another). In this case, I must return back.
Testing
Last updated