poj 1753 Flip Game dfs Tips

dfs has two options of flipping and not flipping, wonderful

#include <iostream>

using namespace std;
int map[4][4];
int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
void turn(int x,int y)
{
    int tx, ty;
    map[x][y]=-map[x][y];
    for(int i=0; i<4; i++)
    {
        tx=x+next[i][1];
        ty=y+next[i][0];
        if(tx<0||ty<0||tx>3||ty>3) continue;
        map [tx] [you] = - map [tx] [you];
    }
}
bool isOk ()
{
    for(int i=0; i<4; i++)
    {
        for(int j=0; j<4; j++)
        {
            if(map[i][j]!=map[0][0])
                return false;
        }
    }
    return true;
}
int years;
int dfs(int x, int y, int step )//There are two options to flip or not to flip, not necessarily to flip both
{
    if (isOk ())
    {
        if(ans>step) ans=step;
        return 0;
    }
    if(x>=4||y>=4) return 0;
    int tx=(x+1)%4;
    int ty = y + (x + 1) / 4;
            dfs(tx,ty,step);
            turn(x,y);
             dfs(tx,ty,step+1);

            turn(x,y);//Return to the original state
            return 0;

}
intmain()
{
    char ch;
    for(int i=0; i<4; i++)
    {
        for(int j=0; j<4; j++)
        {
            cin>>ch;
            if(ch=='b') map[i][j]=1;
            else map[i][j]=-1;
        }
    }
    years=999999;
    dfs(0,0,0);
    if(ans==999999)
        cout<<"Impossible"<<endl;
    else cout<<ans<<endl;
    return 0;
}

2. Compress state with bit operations

First know that XOR with 1 changes the state (0 becomes 1, 1 becomes 0) XOR with 0 does not change the state, which corresponds to the problem of whether or not to flip the chess piece.

For example, turn over the (i, j)th piece, such as j=2, then the i-th row XOR 1110 The i-1th row and the i+1th row XOR 0100 

How to save the state is to use a[4] to represent 4 lines

For example a[1]=1110 then a[1] is 14 

See how others read the data

void read() {
    for(int i=1; i<=4; i++) {
        for(int j=1; j<=4; j++) {
            field[i]<<=1;
            if(getchar()=='b')
                field[i]|=1;
        }
        getchar();
    }
}

Initialize field to 0

 I think if(getchar()=='b') field[i]+=(1<<4-j); also works

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325739505&siteId=291194637