1349. Maximum Students Taking Exam

https://leetcode.com/problems/maximum-students-taking-exam/

Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.

Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..

Students must be placed in seats in good condition.

Input: seats = [["#",".","#","#",".","#"],
                [".","#","#","#","#","."],
                ["#",".","#","#",".","#"]]
Output: 4
Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. 

Example 2:

Input: seats = [[".","#"],
                ["#","#"],
                ["#","."],
                ["#","#"],
                [".","#"]]
Output: 3
Explanation: Place all students in available seats. 

Example 3:

Input: seats = [["#",".",".",".","#"],
                [".","#",".","#","."],
                [".",".","#",".","."],
                [".","#",".","#","."],
                ["#",".",".",".","#"]]
Output: 10
Explanation: Place students in available seats in column 1, 3 and 5.

Constraints:

  • seats contains only characters '.' and'#'.

  • m == seats.length

  • n == seats[i].length

  • 1 <= m <= 8

  • 1 <= n <= 8

由#和.组成的矩阵,当左,右,左上和右上没有放置过人且当前位置为.时,可以放置一个人,问最多能放置多少人。当前行的放置状态只取决于上一行的状态,每一行可能有2^N个状态,因此用N位的bitvec encode状态。dp[i][state]表示前i行且第i行状态为state时最多能放置多少人。对每行做遍历并遍历第i行所有可能的状态,当状态满足左和右没有放置过人且是『.』时,再遍历上一行所有可能的状态,当满足左上和右上条件后统计可放置人数作为dp[i][state]。

参考自

class Solution {
public:    
    int maxStudents(vector<vector<char>>& seats) {
        const int M = seats.size(), N = M == 0 ? 0 : seats[0].size();
        // 检查每行哪个位置是『.』,用bitvec表示
        vector<int> valid(M);
        for (int i = 0; i < M; ++i) {
            int cur = 0;
            for (int j = 0; j < N; ++j) {
                cur = (cur << 1) + (seats[i][j] == '.');
            }
            valid[i] = cur;
        }
        vector<vector<int>> dp(M + 1, vector<int>(1 << N, -1));
        dp[0][0] = 0;
        for (int i = 1; i <= M; ++i) {
            const int v = valid[i - 1];
            // 遍历当前行可能的状态
            for (int j = 0; j < (1 << N); ++j) {
                // 当当前状态是v的子集且j下没有相邻的1
                if ((j & v) == j && !(j & (j >> 1))) {
                    // 遍历上一行所有可能的状态
                    for (int k = 0; k < (1 << N); ++k) {
                        // 当右上和左上都不相邻
                        if (!(j & (k >> 1)) && !((j >> 1) & k) && dp[i - 1][k] != -1) {
                            dp[i][j] = max(dp[i][j], dp[i - 1][k] + __builtin_popcount(j));
                        }
                    }
                }
            }
        }
        return *max_element(begin(dp[M]), end(dp[M]));
    }
};

Last updated