LeetCode 1349. Maximum Students Taking Exam

题目描述

给你一个 m * n 的矩阵 seats 表示教室中的座位分布。如果座位是坏的(不可用),就用 '#' 表示;否则,用 '.' 表示。

学生可以看到左侧、右侧、左上、右上这四个方向上紧邻他的学生的答卷,但是看不到直接坐在他前面或者后面的学生的答卷。请你计算并返回该考场可以容纳的一起参加考试且无法作弊的最大学生人数。

学生必须坐在状况良好的座位上。

样例

输入:seats = [["#",".","#","#",".","#"],
              [".","#","#","#","#","."],
              ["#",".","#","#",".","#"]]
输出:4
解释:教师可以让 4 个学生坐在可用的座位上,这样他们就无法在考试中作弊。 


输入:seats = [[".","#"],
              ["#","#"],
              ["#","."],
              ["#","#"],
              [".","#"]]
输出:3
解释:让所有学生坐在可用的座位上。


输入:seats = [["#",".",".",".","#"],
              [".","#",".","#","."],
              [".",".","#",".","."],
              [".","#",".","#","."],
              ["#",".",".",".","#"]]
输出:10
解释:让学生坐在第 1、3 和 5 列的可用座位上。

算法
 

C++ 代码 

class Solution {
public:
    bool check(const vector<vector<char>>& seats, int i, int s1, int s2, int n) {
        for (int j = 0; j < n; j++)
            if (s2 & (1 << j)) {
                if (seats[i][j] == '#')
                    return false;

                if (j > 0 && ((s1 & (1 << (j - 1))) || (s2 & (1 << (j - 1)))))
                    return false;

                if (j < n - 1 && ((s1 & (1 << (j + 1))) || (s2 & (1 << (j + 1)))))
                    return false;
            }

        return true;
    }

    int maxStudents(vector<vector<char>>& seats) {
        int m = seats.size(), n = seats[0].size();
        vector<vector<int>> f(m + 1, vector<int>(1 << n, 0));
        vector<int> c(1 << n, 0);

        for (int s = 0; s < (1 << n); s++)
            for (int j = 0; j < n; j++)
                if (s & (1 << j))
                    c[s]++;

        f[0][0] = 0;
        for (int i = 1; i <= m; i++)
            for (int s1 = 0; s1 < (1 << n); s1++)
                for (int s2 = 0; s2 < (1 << n); s2++)
                    if (check(seats, i - 1, s1, s2, n))
                        f[i][s2] = max(f[i][s2], f[i - 1][s1] + c[s2]);

        int ans = 0;

        for (int s = 0; s < (1 << n); s++)
            ans = max(ans, f[m][s]);

        return ans;
    }
};
发布了54 篇原创文章 · 获赞 80 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41685265/article/details/104650873