LeetCode 175 Week tournament games: 5335 The maximum number of students taking the exam (like pressure DP).

Give you a m * n matrix representation seats in a classroom seats distribution. If the seat is bad (not available), use '#' indicates; otherwise, denoted by '.'.

Students can see on the left, right, upper left, upper right next to the four directions of his students answer, but students can not see him sitting directly in front of or behind the answer. Please work and returns the maximum number of students taking the exam together and can not cheat the examination room can hold.

Students must be in good condition sitting on the seat.

 

Example 1:

Input: ".". "" Seats = [[ "#",, "#", "#",, "#"],
              . "" [, "#", "#", "#", "# . "," "],
              [" # "," "," # "," # "," "," # "]].
output: 4
to explain: teachers can allow students to sit on the four available seats so they will not be able to cheat in exams. 
Example 2:

Input:. "" Seats = [[, "#"],
              [ "#", "#"],
              [ "#",],. ""
              [ "#", "#"],
              [, "." "#"]]
output: 3
explained: let all the students sitting in available seat.
Example 3:

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

prompt:

seats only character '.' and '#'
m == seats.length
n-seats == [I] .length
. 1 <= m <=. 8
. 1 <= n-<=. 8

Ideas: like pressure DP, enumerate the current status and the previous line of (binary representation), remove the illegal situation, correct implementation of the state transition can be.

class Solution {
    public int maxStudents(char[][] seats) {
     
    	int m=seats.length;
    	int n=seats[0].length;
    	int len=1<<n;
    	int[][] dp=new int[m][len];
    	
    	for(int i=0;i<len;i++) {
    		int num=0;
    		for(int j=0;j<n;j++) {
    			if(((i>>j)&1)!=0) {
    				if(seats[0][j]=='.') num++;
    				else {
    					num=0;
    					break;
    				}
    			}
    			if(j>0 && ((i>>j)&1)==1 && ((i>>j-1)&1)==1) {
    				num=0;
    				break;
    			}
    		}
    		dp[0][i]=num;
    	}
    	
    	for(int i=1;i<m;i++)
    		for(int j=0;j<len;j++) {
    			for(int k=0;k<len;k++) {
    				int num=0;
    				boolean flag=false;
    				for(int h=0;h<n;h++) {
    					int x1=(j>>h-1)&1;
    				    int x2=(j>>h+1)&1;
    				    int x3=(k>>h)&1;
    				    int x4=(k>>h-1)&1;
    				    if(h>0 && x1+x3==2 || h<n-1 && x2+x3==2 || h>0 && x3+x4==2 || seats[i][h]=='#' && x3==1)
    				    	flag=true;
    					if(((k>>h)&1)==1) num++;
    				}
    				if(!flag) dp[i][k]=Math.max(dp[i][k], dp[i-1][j]+num);
    			}
    		}
    	
    	int ans=0;
    	for(int i=0;i<len;i++) 
    		ans=Math.max(ans, dp[m-1][i]);
    	
    	return ans;
    }
}

 

发布了987 篇原创文章 · 获赞 175 · 访问量 21万+

Guess you like

Origin blog.csdn.net/haut_ykc/article/details/104235793