[LeetCode] Maximum Students Taking Exam

1349. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
int dp[8][1<<9];
unordered_set<int> makeCombination(vector<int>& seat, int p) {
if(p == seat.size()) return {};
unordered_set<int> res{1<<(seat[p])};

res.insert(1<<(seat[p]));
auto ans = makeCombination(seat, p + 1);
for(auto comb : ans) {
res.insert(comb);
if(comb & 1<<(seat[p] + 1)) continue;
res.insert(comb | 1<<(seat[p]));
}
return res;
}
int helper(vector<vector<char>>& seats, int mask, int row) {
int n = seats.size(), m = seats[0].size();
if(row == n) return 0;
if(dp[row][mask] != -1) return dp[row][mask];

int& res = dp[row][mask] = helper(seats, 0, row + 1);

vector<int> seat;
for(int i = 0; i < m; i++) {
if(seats[row][i] == '#') continue;
if(mask & 1<<(i + 1) or (i > 0 and mask & 1<<(i - 1))) continue;
seat.push_back(i);
}

unordered_set<int> combinations = makeCombination(seat, 0);
for(auto combination : combinations) {
res = max(res, helper(seats, combination, row + 1) + __builtin_popcount(combination));
}

return res;
}
public:
int maxStudents(vector<vector<char>>& seats) {
memset(dp,-1,sizeof(dp));
return helper(seats, 0ull, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/10/PS/LeetCode/maximum-students-taking-exam/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.