标签:
碰巧与前一篇leetcode题目相同,解法是类似leetcode generate valid paranthesis的dfs (要是能刷几遍leetcode, cc150就能举一反三,触类旁通,何必大费周折,哎)
不算之前一知半解的二维树状数组,这题算是正式踏入POJ大门了
核心思想:对于当前棋盘状态有两种选择:1.不翻转当前方格,继续深搜下一个位置 2.翻转当前位置,深搜下一个位置,回溯
1 #include<stdio.h> 2 #include<iostream> 3 4 using namespace std; 5 6 int chess[4][4]; 7 int moves = 17; // 4*4+1 8 9 void buildBoard() { 10 char c; 11 for (int i = 0; i < 4; i++) { 12 for (int j = 0; j < 4; j++) { 13 cin >> c; 14 if (c == ‘w‘) chess[i][j] = 0; 15 else chess[i][j] = 1; 16 } 17 } 18 } 19 20 void turn(int x, int y) { 21 if (x >= 0 && y >= 0 && x < 4 && y < 4) { 22 chess[x][y] = !chess[x][y]; 23 } 24 } 25 26 void flip(int num) { 27 int i = num / 4; 28 int j = num % 4; 29 30 turn(i, j); 31 turn(i+1, j); 32 turn(i, j+1); 33 turn(i-1, j); 34 turn(i, j-1); 35 } 36 37 bool allSame() { 38 int sum = 0; 39 for (int i = 0; i < 4; i++) { 40 for (int j = 0; j < 4; j++) { 41 sum += chess[i][j]; 42 } 43 } 44 return !(sum % 16); 45 } 46 47 void dfs(int pos, int num_flipped) { 48 49 if (allSame()) { 50 if (num_flipped < moves) moves = num_flipped; 51 return; 52 } 53 if (pos >= 16) return; 54 dfs(pos+1, num_flipped); 55 flip(pos); 56 dfs(pos+1, num_flipped+1); 57 flip(pos); 58 } 59 60 int main() { 61 buildBoard(); 62 dfs(0, 0); 63 if (moves == 17) { 64 cout << "Impossible" << endl; 65 } else { 66 cout << moves << endl; 67 } 68 return 0; 69 }
标签:
原文地址:http://www.cnblogs.com/ilovenaomi/p/4885147.html