POJ 1753 Flip Game(枚举+dfs)

来源:互联网 发布:美国7月非农数据 编辑:程序博客网 时间:2024/05/17 21:06




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





题目大意:

翻棋子   类似于黑白棋    不同的是在翻的时候连同它上下左右的棋子一起翻    问最少要翻多少次能使棋子全部为白色或者全部为黑色


分析:

枚举翻的棋子数    在每种翻的棋子数下按行搜索所有情况  一但有全为白色或黑色   则找到最小次数






AC代码:

#include <stdio.h>#include <string.h>char map[20][20];int step;int flag;int judge(){//      判断全白或全黑     for (int i=0;i<4;i++){        for (int j=0;j<4;j++){            if(map[i][j]!=map[0][0])                return 0;        }    }    return 1;}void oper(int x,int y){//    翻棋操作     if (map[x][y]=='b')        map[x][y]='w';    else    map[x][y]='b';    if (x-1>=0)        if (map[x-1][y]=='b')        map[x-1][y]='w';    else    map[x-1][y]='b';    if (x+1<4)       if (map[x+1][y]=='b')        map[x+1][y]='w';    else    map[x+1][y]='b';    if (y-1>=0)       if (map[x][y-1]=='b')        map[x][y-1]='w';    else    map[x][y-1]='b';    if (y+1<4)        if (map[x][y+1]=='b')        map[x][y+1]='w';    else    map[x][y+1]='b';}void dfs(int x,int y,int count){    if(count==step){    flag=judge();    return ;}if(flag||x==4)return;//        翻牌 oper(x,y);    if(y<3)    dfs(x,y+1,count+1);    else    dfs(x+1,0,count+1);        oper(x,y);    //       不翻牌     if(y<3)    dfs(x,y+1,count);    else    dfs(x+1,0,count);}int main (){    memset(map,0,sizeof(map));    for (int i=0;i<4;i++){        scanf ("%s",map[i]);    }     for(step=0;step<=16;step++){    flag=0;    dfs(0,0,0);    if(flag)    break;}        if (!flag)        printf ("Impossible\n");    else        printf ("%d\n",step);    return 0;}


原创粉丝点击