Timus 1060. Flip Game

来源:互联网 发布:java高德地图api接口 编辑:程序博客网 时间:2024/06/10 12:54

原题:1060. Flip Game

解法:直接dfs

#include <iostream>#include <string.h>#include <stdlib.h>using namespace std;int d[5][3] = {{0,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};int a[5][5] = {0}, ans = 20;int dfs(int x, int y, int z) {    if (z >= ans) return 0;    bool flag = true;    for (int i = 1; i <= 4; i++)        for (int j = 1; j <= 4; j++) flag = flag && (a[i][j] == a[1][1]);    if (flag) {        ans = z;        return 0;    }    if (x > 4) return 0;    int x1, y1;    x1 = x; y1 = y+1;    if (y1 > 4) {        y1 = 1;        x1++;    }    dfs(x1, y1, z);    for (int k = 0; k <= 4; k++) {        int p = x+d[k][1];        int q = y+d[k][2];        if (p < 1 || p > 4 || q < 1 || q > 4) continue;        a[p][q] = 1-a[p][q];    }    dfs(x1, y1, z+1);    for (int k = 0; k <= 4; k++) {        int p = x+d[k][1];        int q = y+d[k][2];        if (p < 1 || p > 4 || q < 1 || q > 4) continue;        a[p][q] = 1-a[p][q];    }}int main() {    char c;    for (int i = 1; i <= 4; i++) {        for (int j = 1; j <= 4; j++) {            cin >> c;            if (c == 'b') a[i][j] = 1;            else a[i][j] = 0;        }    }    dfs(1,1,0);    if (ans == 20) cout << "Impossible" << endl;    else cout << ans << endl;}
0 0