Walls and Gates
Problem
Approach
The problem is given in the form of int[][] but it can be modelled to form of graph. When we model it in the form of graph, we can apply BFS which optimally finds the solution in least amount of time.
We create a queue
Add all existing gates to the queue
Process the queue until empty
Poll the cell from queue
Explore up, down, left and right sides from the polled cell
Make sure the coordinates which were generated from polled cell, are valid. Valid means:
Coordinates value should not be less than zero
Coordinates value should not be greater than equal to size of the graph
Should not be a wall
Once we make sure, it is a valid cell to be processed, we increment the new cell value by 1 with value from polled cell
Add the new cell to queue for further processing
We add the new cell too queue because, they are part of solution and we have not yet processed the cell completely. Using BFS makes sure, we process each cell only once.
Complexity
V -> Vertices (cells)
E -> Edges (connection between the cells)
The walls are not vertices in the graph, so they are not processed by the BFS algorithm.
Time Complexity:
O(|V|+|E|)
It follows standard BFS algorithm. We explore all the cells before we process cells which are not walls. And during the processing of cells in the queue, we need to explore their edges i.e. up, down, right and left.
Space Complexity
O(|V|)
Even though we are only processing cells which are not walls. This is because the algorithm still needs to store a queue of size |V|. The queue is used to store the vertices that have not yet been visited.
Code
Last updated