poj1753

暴力dfs

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

bool map[4][4];
int ans = 100;

void init()
{
    int i, j;

    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 4; j++)
        {
            char ch;
            cin >> ch;
            if (ch == 'b')
                map[i][j] = true;
            else
                map[i][j] = false;
        }
        getchar();
    }
}

void operate(int x, int y)
{
    if (x < 0 || y < 0 || x > 3 || y > 3)
        return;
    map[x][y] = !map[x][y];
}

void turn(int pos)
{
    int x = pos / 4;
    int y = pos % 4;
    operate(x, y);
    operate(x + 1, y);
    operate(x, y + 1);
    operate(x - 1, y);
    operate(x, y - 1);
}

bool finished()
{
    int tot = 0;
    int i;
    for (i = 0; i < 16; i++)
        tot += map[i / 4][i % 4];
    return ((tot % 16) == 0);
}

void dfs(int pos, int step)
{
    if (finished())
    {
        if (ans > step)
            ans = step;
        return;
    }
    if (pos >= 16)
        return;
    dfs(pos + 1, step);
    turn(pos);
    dfs(pos + 1, step + 1);
    turn(pos);
}

int main()
{
    //freopen("D:\t.txt", "r", stdin);
    init();
    dfs(0, 0);
    if (ans == 100)
        cout << "Impossible" << endl;
    else
        cout << ans << endl;
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/rainydays/p/3203999.html