Zoning
InterviewTime limit2sMemory limit512 MB
Given an n by n grid labeled 1, 2, 3, find the maximum over all cells labeled 1 of the Manhattan distance to the nearest cell labeled 3.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Matrix, Shortest path
- Solved
- No attempts yet
Problem
A town is usually divided into zones such as industrial zones, commercial zones, and residential zones. If a residential zone sits far away from every commercial zone, the people who live there face a long trip whenever they want to go shopping, and that is undesirable.
The town is given as an grid of square zones. Each zone is labeled 1 for residential, 2 for industrial, or 3 for commercial. When you travel from one zone to another you may move north, east, south, or west, and the distance travelled is the number of zone boundaries you cross. So the distance between two adjacent zones is 1, and the distance from the zone in square , the most south westerly zone, to the zone in square is 3: one step east and two steps north. You may never move off the grid.
For every residential zone, measure the distance to the commercial zone closest to it. Report the largest of those distances.
Input
The first line contains an integer (). Each of the next lines contains a string of length , giving the map of the town as an matrix where every entry is 1, 2, or 3 according to the zone type. The town contains at least one zone of each of the three types.
Output
Print a single integer , the largest distance from a residential zone to its closest commercial zone.