It happened to be the same as the previous article Leetcode, the solution is similar to Leetcode generate valid Paranthesis DFS (if can brush a few times leetcode, cc150 can extrapolate, comprehend by analogy, why big cost, hey)
Not counting the two-dimensional tree array before smattering, this is officially stepping into the POJ gate.
Core idea: There are two options for the current checkerboard State: 1. Do not flip the current grid, continue to deep search the next position 2. Flip the current position, deep search the next position, backtracking
1#include <stdio.h>2#include <iostream>3 4 using namespacestd;5 6 intchess[4][4];7 intMoves = -;//4*4+18 9 voidBuildboard () {Ten CharC; One for(inti =0; I <4; i++) { A for(intj =0; J <4; J + +) { -CIN >>C; - if(c = ='W') Chess[i][j] =0; the ElseCHESS[I][J] =1; - } - } - } + - voidTurnintXinty) { + if(x >=0&& y >=0&& x <4&& y <4) { AChess[x][y] =!Chess[x][y]; at } - } - - voidFlipintnum) { - inti = num/4; - intj = num%4; in - Turn (i, j); toTurn (i+1, j); +Turn (i, j+1); -Turn (I-1, j); theTurn (i, J-1); * } $ Panax Notoginseng BOOLAllsame () { - intsum =0; the for(inti =0; I <4; i++) { + for(intj =0; J <4; J + +) { ASum + =Chess[i][j]; the } + } - return! (Sum% -); $ } $ - voidDfsintPosintnum_flipped) { - the if(Allsame ()) { - if(num_flipped < moves) moves =num_flipped;Wuyi return; the } - if(Pos >= -)return; WuDFS (pos+1, num_flipped); - Flip (POS); AboutDFS (pos+1, num_flipped+1); $ Flip (POS); - } - - intMain () { A Buildboard (); +Dfs0,0); the if(Moves = = -) { -cout <<"Impossible"<<Endl; $}Else { thecout << moves <<Endl; the } the return 0; the}
Fifth Chapter poj1753 Flip Game