|
| 1 | +/** |
| 2 | + * 1349. Maximum Students Taking Exam |
| 3 | + * https://leetcode.com/problems/maximum-students-taking-exam/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is |
| 7 | + * broken, it is denoted by '#' character otherwise it is denoted by a '.' character. |
| 8 | + * |
| 9 | + * Students can see the answers of those sitting next to the left, right, upper left and upper |
| 10 | + * right, but he cannot see the answers of the student sitting directly in front or behind him. |
| 11 | + * Return the maximum number of students that can take the exam together without any cheating |
| 12 | + * being possible. |
| 13 | + * |
| 14 | + * Students must be placed in seats in good condition. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {character[][]} seats |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var maxStudents = function(seats) { |
| 22 | + const rows = seats.length; |
| 23 | + const cols = seats[0].length; |
| 24 | + const cache = new Map(); |
| 25 | + |
| 26 | + return countStudents(0, 0); |
| 27 | + |
| 28 | + function isValid(row, currMask, prevMask) { |
| 29 | + for (let j = 0; j < cols; j++) { |
| 30 | + if (!(currMask & (1 << j))) continue; |
| 31 | + if (seats[row][j] === '#') return false; |
| 32 | + if (j > 0 && (currMask & (1 << (j - 1)))) return false; |
| 33 | + if (j < cols - 1 && (currMask & (1 << (j + 1)))) return false; |
| 34 | + if (row > 0) { |
| 35 | + if (j > 0 && (prevMask & (1 << (j - 1)))) return false; |
| 36 | + if (j < cols - 1 && (prevMask & (1 << (j + 1)))) return false; |
| 37 | + } |
| 38 | + } |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + function countStudents(row, prevMask) { |
| 43 | + if (row === rows) return 0; |
| 44 | + const key = `${row},${prevMask}`; |
| 45 | + if (cache.has(key)) return cache.get(key); |
| 46 | + |
| 47 | + let maxCount = 0; |
| 48 | + for (let currMask = 0; currMask < (1 << cols); currMask++) { |
| 49 | + if (!isValid(row, currMask, prevMask)) continue; |
| 50 | + const students = (currMask.toString(2).match(/1/g) || []).length; |
| 51 | + maxCount = Math.max(maxCount, students + countStudents(row + 1, currMask)); |
| 52 | + } |
| 53 | + |
| 54 | + cache.set(key, maxCount); |
| 55 | + return maxCount; |
| 56 | + } |
| 57 | +}; |
0 commit comments