You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[LeetCode] 1349. Maximum Students Taking Exam #1349
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
这道题说是给了一个 m by n 大小的矩阵,其中点 . 的位置表示好着的椅子,井字号 # 表示坏了的椅子,不能坐人。考生可以坐在好着的椅子上考试,说是考生可以看到其左右两边,以及左前方,右前方人的答案,为了防止作弊发生,上述四个位置不能坐人,问给定的矩阵最多可以坐多少个考生。博主最先看到这题时,感觉有点像八皇后问题的变形,矩阵就是个棋盘,每个考生就是削弱版的皇后,只能覆盖到左右,左前,右前四个位置。想到这,博主最先尝试的使用递归来做的,也就是遍历所有的情况,吭哧吭哧写好后,发现在超大 test case 上超时了,看了下没通过的测例,好多好多1连在一起,一般的递归可能会存在大量的重复计算,非常不高效。后来参考了网上各位大神们的解法,发现普遍都是用的位运算的思路,利用二进制当 mask 来表示特定的状态。比如用1表示好椅子,0表示坏椅子,那么对于例子1中的第一行 ["#",".","#","#",".","#"],就可以用二进制数 010010 来表示,也就是十进制数 18,那么给定的矩阵每一行都可以用一个二进制来表示,这里使用一个数组 avail,其中 avail[i] 表示第i排的座位的二进制数的表示,注意这里从第一排开始算的,所以整个数组设定大小为9。下面来更新这个 avail 数组,一排一排的更新,对于第i排,遍历每一个位置,若该位置是好椅子,则将对应位置变为1,即'或'上 1<<j 即可。
Activity
[-][LeetCode] 1349. Missing Problem[/-][+][LeetCode] 1349. Maximum Students Taking Exam[/+]