Amazon has a 2D grid of cell towers. All servers need to be updated to the latest software version. Servers that already have the update should not be updated again. Servers are in the form of a 2D array of 0 and 1 where the value 0 represents an out of date server and the value of 1 represents an updated server. In a single day, an updated server can push the update to each of its adjacent out of date servers. An adjacent server is either on the left, right, above or below a given server. Once the server receives the update, it becomes updated and can push the update to its adjacent servers on the following day. Given the 2D array representing the current status of its servers.
Write an algorithm that will determine the minimum number of days required to push the update to all the available servers.
Input The input to the function/method consists of three arguments:
- rows, an integer representing the number of rows in the grid;
- columns, an integer representing the number of columns in the grid;
- grid, an integer array representing the current status of its servers. The value 0 represents an out of date server and the value 1 represents an updated server.
Output Return an integer representing the minimum number of days required to update all the servers in the grid network. Return -1 if all the available servers cannot be updated.
Note Diagonally placed cells are not considered neighbors.
Example
Input:
rows = 4
columns = 5
[[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0]]
Output:
2
Explanation: At the end of day one, the status of the servers :
1, 1, 1, 1, 1
1, 1, 1, 1, 1
0, 1, 0, 1, 1
1, 1, 1, 0, 1
at the end of day two, the status of the servers :
1, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 1, 1, 1, 1
By the end of day two, all the servers are up to date.
Assumptions added by Mykola:
- if all servers are already updated - return
0
- if there are no servers (rows or columns) - return
-1
- edge cell doesn't update a server on the opposite side
ex:
[[1, 0, 0, 0]]
will be[1, 1, 0, 0]
on the first day but not[[1, 1, 0, 1]]