poj 1753 翻转棋子

题目大意:

 http://poj.org/problem?id=1753

翻转棋子,每个棋子只能翻转一次,因为翻转两次的效果是没翻,翻转三次的效果和翻转一次一样。。。

 

代码:

#include <iostream>

using namespace std;

int arr[4][4] = {0};
int mv[5][2] = {{0,0},{0,1},{0,-1},{1,0},{-1,0}};
int count = 17;

bool check()
{
    int tmp = arr[0][0];
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 4; j++)
            if(tmp != arr[i][j])
                return false;

    return true;
}

void reverse(int x, int y)
{
    for(int i = 0; i < 5; i++){
        int xx = x + mv[i][0];
        int yy = y + mv[i][1];

        if(xx >= 0 && xx < 4 && yy >= 0 && yy < 4){
            arr[xx][yy] = !arr[xx][yy];
        }
    }
}

void dfs(int x,int y,int step)
{
    if(check()){
        count = min(step,count);
        return;
    }
    if(step == 17)
        return;
     if (x >= 4 || y >= 4)  
        return; 

    int nx = (x+1)%4;
    int ny = y + (x+1)/4;
    dfs(nx,ny,step);
    reverse(x,y);
    dfs(nx,ny,step+1);
    reverse(x,y);
    return;
}


int main()
{
    for(int i = 0; i < 4;i++){
        for(int j = 0; j < 4;j++){
            char ch;
            cin >> ch;
            if(ch == 'b')
                arr[i][j] = 0;
            else
                arr[i][j] = 1;
        }
    }

    dfs(0,0,0);
    if(count >= 17)
        cout << "Impossible" << endl;
    else
        cout << count << endl;

    return 0;
}

 

posted @ 2017-12-21 14:29  prog123  阅读(233)  评论(0编辑  收藏  举报