Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1349.html

1349. Maximum Students Taking Exam (Hard)

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.

 

Example 1:

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

Related Topics:
Dynamic Programming

Solution 1. DP

// OJ: https://leetcode.com/problems/maximum-students-taking-exam/
// Time: O(M * (2^N)^2)
// Space: O(M * 2^N)
// Ref: https://leetcode.com/problems/maximum-students-taking-exam/discuss/503686/A-simple-tutorial-on-this-bitmasking-problem
class Solution {
public:
    int maxStudents(vector<vector<char>>& A) {
        int M = A.size(), N = A[0].size();
        vector<int> states;
        for (int i = 0; i < M; ++i) {
            int cur = 0;
            for (int j = 0; j < N; ++j) cur = cur * 2 + (A[i][j] == '.');
            states.push_back(cur);
        }
        vector<vector<int>> dp(M + 1, vector<int>(1 << N, -1));
        dp[0][0] = 0;
        for (int i = 1; i <= M; ++i) {
            int state = states[i - 1];
            for (int j = 0; j < (1 << N); ++j) {
                if ((j & state) != j || (j & (j >> 1))) continue;
                int cnt = __builtin_popcount(j);
                for (int k = 0; k < (1 << N); ++k) {
                    if ((j & (k >> 1)) || (j & (k << 1)) || dp[i - 1][k] == -1) continue;
                    dp[i][j] = max(dp[i][j], dp[i - 1][k] + cnt);
                }
            }
        }
        return *max_element(begin(dp[M]), end(dp[M]));
    }
};
  • class Solution {
        public int maxStudents(char[][] seats) {
            int rows = seats.length, columns = seats[0].length;
            int[][] dp = new int[rows][1 << columns];
            for (int state = 0; state < 1 << columns; state++) {
                if (isLegal(seats, 0, state))
                    dp[0][state] = Integer.bitCount(state);
            }
            for (int i = 1; i < rows; i++) {
                for (int state1 = 0; state1 < 1 << columns; state1++) {
                    for (int state2 = 0; state2 < 1 << columns; state2++) {
                        if (isLegal(seats, i - 1, state1) && isLegal(seats, i, state2) && isLegal(state1, state2))
                            dp[i][state2] = Math.max(dp[i][state2], dp[i - 1][state1] + Integer.bitCount(state2));
                    }
                }
            }
            int maxStudents = 0;
            for (int state = 0; state < 1 << columns; state++)
                maxStudents = Math.max(maxStudents, dp[rows - 1][state]);
            return maxStudents;
        }
    
        public boolean isLegal(char[][] seats, int row, int state) {
            if ((state << 1 & state) != 0 || (state >> 1 & state) != 0)
                return false;
            int columns = seats[0].length;
            boolean[] curRow = new boolean[columns];
            for (int i = columns - 1; i >= 0; i--) {
                curRow[i] = state % 2 == 1;
                state /= 2;
            }
            for (int i = 0; i < columns; i++) {
                if (seats[row][i] == '#' && curRow[i])
                    return false;
            }
            return true;
        }
    
        public boolean isLegal(int state1, int state2) {
            return (state1 << 1 & state2) == 0 && (state1 >> 1 & state2) == 0;
        }
    }
    
    ############
    
    class Solution {
        private Integer[][] f;
        private int n;
        private int[] ss;
    
        public int maxStudents(char[][] seats) {
            int m = seats.length;
            n = seats[0].length;
            ss = new int[m];
            f = new Integer[1 << n][m];
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (seats[i][j] == '.') {
                        ss[i] |= 1 << j;
                    }
                }
            }
            return dfs(ss[0], 0);
        }
    
        private int dfs(int seat, int i) {
            if (f[seat][i] != null) {
                return f[seat][i];
            }
            int ans = 0;
            for (int mask = 0; mask < 1 << n; ++mask) {
                if ((seat | mask) != seat || (mask & (mask << 1)) != 0) {
                    continue;
                }
                int cnt = Integer.bitCount(mask);
                if (i == ss.length - 1) {
                    ans = Math.max(ans, cnt);
                } else {
                    int nxt = ss[i + 1];
                    nxt &= ~(mask << 1);
                    nxt &= ~(mask >> 1);
                    ans = Math.max(ans, cnt + dfs(nxt, i + 1));
                }
            }
            return f[seat][i] = ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/maximum-students-taking-exam/
    // Time: O(M * (2^N)^2)
    // Space: O(M * 2^N)
    // Ref: https://leetcode.com/problems/maximum-students-taking-exam/discuss/503686/A-simple-tutorial-on-this-bitmasking-problem
    class Solution {
    public:
        int maxStudents(vector<vector<char>>& A) {
            int M = A.size(), N = A[0].size();
            vector<int> states;
            for (int i = 0; i < M; ++i) {
                int cur = 0;
                for (int j = 0; j < N; ++j) cur = cur * 2 + (A[i][j] == '.');
                states.push_back(cur);
            }
            vector<vector<int>> dp(M + 1, vector<int>(1 << N, -1));
            dp[0][0] = 0;
            for (int i = 1; i <= M; ++i) {
                int state = states[i - 1];
                for (int j = 0; j < (1 << N); ++j) {
                    if ((j & state) != j || (j & (j >> 1))) continue;
                    int cnt = __builtin_popcount(j);
                    for (int k = 0; k < (1 << N); ++k) {
                        if ((j & (k >> 1)) || (j & (k << 1)) || dp[i - 1][k] == -1) continue;
                        dp[i][j] = max(dp[i][j], dp[i - 1][k] + cnt);
                    }
                }
            }
            return *max_element(begin(dp[M]), end(dp[M]));
        }
    };
    
  • class Solution:
        def maxStudents(self, seats: List[List[str]]) -> int:
            def f(seat: List[str]) -> int:
                mask = 0
                for i, c in enumerate(seat):
                    if c == '.':
                        mask |= 1 << i
                return mask
    
            @cache
            def dfs(seat: int, i: int) -> int:
                ans = 0
                for mask in range(1 << n):
                    if (seat | mask) != seat or (mask & (mask << 1)):
                        continue
                    cnt = mask.bit_count()
                    if i == len(ss) - 1:
                        ans = max(ans, cnt)
                    else:
                        nxt = ss[i + 1]
                        nxt &= ~(mask << 1)
                        nxt &= ~(mask >> 1)
                        ans = max(ans, cnt + dfs(nxt, i + 1))
                return ans
    
            n = len(seats[0])
            ss = [f(s) for s in seats]
            return dfs(ss[0], 0)
    
    
  • func maxStudents(seats [][]byte) int {
    	m, n := len(seats), len(seats[0])
    	ss := make([]int, m)
    	f := make([][]int, 1<<n)
    	for i, seat := range seats {
    		for j, c := range seat {
    			if c == '.' {
    				ss[i] |= 1 << j
    			}
    		}
    	}
    	for i := range f {
    		f[i] = make([]int, m)
    		for j := range f[i] {
    			f[i][j] = -1
    		}
    	}
    	var dfs func(int, int) int
    	dfs = func(seat, i int) int {
    		if f[seat][i] != -1 {
    			return f[seat][i]
    		}
    		ans := 0
    		for mask := 0; mask < 1<<n; mask++ {
    			if (seat|mask) != seat || (mask&(mask<<1)) != 0 {
    				continue
    			}
    			cnt := bits.OnesCount(uint(mask))
    			if i == m-1 {
    				ans = max(ans, cnt)
    			} else {
    				nxt := ss[i+1] & ^(mask >> 1) & ^(mask << 1)
    				ans = max(ans, cnt+dfs(nxt, i+1))
    			}
    		}
    		f[seat][i] = ans
    		return ans
    	}
    	return dfs(ss[0], 0)
    }
    
    func max(a, b int) int {
    	if a > b {
    		return a
    	}
    	return b
    }
    

All Problems

All Solutions