Walls and Gates with the Most Assigned Rooms
You are given a grid containing walls, gates, and empty rooms. Assign every reachable empty room to its nearest gate and return the gate or gates assigned to the largest number of rooms.
Grid Representation
- Each string represents one row of the grid.
- Values within a row are separated by commas.
-1 represents a wall or obstacle.
0 represents a gate.
2147483647 represents an empty room.
Distance Rules
- Movement is allowed one cell up, down, left, or right.
- Walls cannot be crossed.
- Each reachable empty room is assigned to a gate having the minimum distance from it.
- If multiple gates are equally near, assign the room to the gate with the smaller row index.
- If the row indices are also equal, assign it to the gate with the smaller column index.
- An empty room that cannot reach any gate is not assigned to a gate.
- Gate cells themselves are not counted as assigned rooms.
Result Rules
- Return every gate assigned to the maximum number of empty rooms.
- Gates with no assigned rooms are still considered. If no empty room is assigned to any gate, return every gate because all gates are tied with zero assigned rooms.
- Represent each gate as
"row,column", using zero-based indices.
- Return the gates in ascending row order and then ascending column order.
- If the grid contains no gates, return an empty list.
Method
Find Most Common Gates
List<String> findMostCommonGates(List<String> grid)
Return the coordinates of the gate or gates assigned to the largest number of reachable empty rooms.
Constraints
1 ≤ grid.size() ≤ 500
1 ≤ number of values in each row ≤ 500
- Every row contains the same number of values.
- Each value is
-1, 0, or 2,147,483,647.
- Values in each row are separated by commas without spaces.
Examples
Example 1
findMostCommonGates(grid = ["2147483647,2147483647,0","-1,2147483647,-1","0,2147483647,2147483647"])
Output: ["0,2"]
The gate at row 0, column 2 is selected by more empty rooms than the other gate.
Example 2
findMostCommonGates(grid = ["0,-1,0","2147483647,-1,2147483647"])
Output: ["0,0","0,2"]
Both gates are assigned the same maximum number of rooms, so both coordinates are returned in row and column order.
Example 3
findMostCommonGates(grid = ["2147483647,-1","-1,2147483647"])
Output: []
The grid contains no gates.