Problem Description
We are given an n x n grid and a list of lamp locations that are initially turned on. When a lamp is on, it illuminates its entire row, column, and both diagonals. For a series of queries asking if a particular cell is illuminated, we must return 1 if it is illuminated or 0 otherwise. After each query, we turn off any lamp (if present) at the query cell and its 8 adjacent cells.
Key Insights
- Use hash maps (or dictionaries) to track the count of active lamps in each row, column, diagonal (r - c), and anti-diagonal (r + c) so that checking illumination for any cell becomes O(1).
- Use a set to maintain the active lamp positions and to avoid duplicate processing.
- For each query, check if any corresponding count (for the cell’s row, column, diags) is positive; if yes, the cell is illuminated.
- Turn off all lamps in the 3 x 3 neighborhood around the query cell and update all maps accordingly.
- Efficiently updating and checking data structures is crucial given the constraints.
Space and Time Complexity
Time Complexity: O(L + Q) on average, where L is the number of lamps and Q is the number of queries. Each query and each lamp update is O(1) average due to hash map and set operations. Space Complexity: O(L), for storing lamp positions and the counters.
Solution
We maintain four hash maps for rows, columns, diagonals, and anti-diagonals. All active lamp positions are stored in a set. During initialization, we add each lamp to our set and update the counters. For each query, we check if the queried cell is illuminated by any lamp using our maps. Then we iterate over the query cell and its 8 adjacent positions, removing any lamp present and decrementing the corresponding counts.