Problem Description
Given an m x n matrix representing the classroom seats (where '.' represents a good seat and '#' a broken one), determine the maximum number of students that can sit in the classroom such that no cheating occurs. A student can see the answer sheets of adjacent students to his left, right, upper left, and upper right. Hence, two students must not be positioned in seats where one can see the other's exam.
Key Insights
- Use bitmasking to represent each row's seating arrangement; each bit corresponds to whether a student is seated.
- Pre-calculate all possible valid configurations (bitmasks) for each row that respect the “no adjacent students in the same row (left/right)” rule and account for broken seats.
- Use dynamic programming with state transition between rows while making sure that the current row’s configuration does not conflict with the previous row’s configuration (i.e. avoid cheating from upper left and upper right positions).
- Transition validation between rows is achieved by ensuring that no student in the current row has a cheating conflict with a student in the previous row (check (prev_mask << 1) and (prev_mask >> 1) against current mask).
Space and Time Complexity
Time Complexity: O(m * 2^n * 2^n) – For each of m rows, we iterate over all valid masks (at most 2^n) and check compatibility with each valid mask from the previous row. Space Complexity: O(m * 2^n) – DP table stores up to m rows with 2^n states each.
Solution
The solution uses bitmask dynamic programming to explore valid student seating arrangements row by row:
- Convert each row of seats into a bitmask (masking out broken seats).
- For each row, enumerate all valid masks where no two seated students are adjacent.
- Use a DP array where dp[row][mask] indicates the maximum number of students seated up to that row using the configuration represented by mask.
- For each row (after the first), iterate over all valid current masks and all valid previous masks, ensuring that the cheating condition is not violated by checking that no student in the current mask is directly diagonally adjacent (upper left or upper right) to any student in the previous mask.
- Finally, the answer is the maximum value in the DP table for the last row.