格子游戏Grid game CodeForce#1104C 模拟
题目链接:Grid game
题目原文
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.
题目大意
给一个4x4的格子,在上面放置1x2或者2x1的方块。如果方块占满了一行或者一列,就可以消除这一行或者这一列。问放置方块的方案。
思路
一开始想的是,直接放,找到第一个能放的位置就放下来,但是这个思路在test14会WA。这个思路的问题在于,消去的过程中可能会产生几个孤立的点,影响后续的放置。解决办法是只要竖着放置的方块和横着放置的方块互不干扰,两个横排的和四个竖排的能自己相消,就不会产生孤立的不能放的地方。也就是用两排专门横放,两排专门竖放就可以了。直接改一下循环时候的界限就AC了。(不过这样的话代码就比较乱了)
题解
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 int map[4][4]; 7 string s; 8 9 10 void detect(int x) 11 { 12 bool flag = true; 13 for(int i = 0; i < 4; i++) 14 { 15 if(map[x][i] == 0) flag = false; 16 } 17 if(flag) 18 { 19 for(int i = 0; i < 4; i++) 20 { 21 map[x][i] = 0; 22 } 23 return; 24 } 25 flag = true; 26 for(int i = 0; i < 4; i++) 27 { 28 if(map[i][x] == 0) flag = false; 29 } 30 if(flag) 31 { 32 for(int i = 0; i < 4; i++) 33 { 34 map[i][x] = 0; 35 } 36 return; 37 } 38 } 39 40 void put(char c) 41 { 42 if(c == '0') 43 { 44 for (int j = 0; j < 3; ++j) 45 { 46 for (int k = 0; k < 4; ++k) 47 { 48 if(!map[j][k] && !map[j+1][k]) 49 { 50 map[j][k] = 1; 51 map[j+1][k] = 1; 52 cout << j+1 << " " << k+1 << endl; 53 detect(j); 54 detect(k); 55 detect(j+1); 56 return; 57 } 58 } 59 } 60 } 61 else 62 { 63 for (int j = 2; j < 4; ++j) 64 { 65 for (int k = 0; k < 3; ++k) 66 { 67 if(!map[j][k] && !map[j][k+1]) 68 { 69 map[j][k] = 1; 70 map[j][k+1] = 1; 71 cout << j+1 << " " << k+1 << endl; 72 detect(j); 73 detect(k); 74 detect(k+1); 75 return; 76 } 77 } 78 } 79 } 80 } 81 82 int main() 83 { 84 cin >> s; 85 for(int i = 0; i < s.length(); i++) 86 { 87 put(s[i]); 88 } 89 }