poj dfs相关之2965 The Pilots Brothers’ refrigerator
Accepted 144K 922MS
跟flip game基本一样,只是要用vector记录一下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int n, k, ans;
bool IsFind, arr[6][6];
struct point
{
int x;
int y;
};
vector<point> record;
bool check()
{
int i, j;
for (i = 1; i <= 4;i++)
for (j = 1; j <= 4; j++)
{
if (!arr[i][j])
return false;
}
return true;
}
void flip(int row, int col)
{
int i;
arr[row][col] = !arr[row][col];
for (i = 1; i <= 4; i++)
arr[row][i] = !arr[row][i];
for (i = 1; i <= 4; i++)
arr[i][col] = !arr[i][col];
}
void Print()
{
printf("%d\n", ans);
for (int i = 0; i < record.size(); i++)
printf("%d %d\n", record[i].x, record[i].y);
}
void dfs(int row,int col,int dep)
{
if (dep == ans)
{
if (check()&&!IsFind)
{
IsFind = true;
Print();
}
return;
}
if (row>4 || col > 4 || IsFind)
return;
point cur1;
cur1.x = row;
cur1.y = col;
record.push_back(cur1);
flip(row, col);
if (col < 4)
dfs(row, col + 1, dep + 1);
else
dfs(row + 1, 1, dep + 1);
flip(row, col);
record.pop_back();
if (col < 4)
dfs(row, col + 1, dep);
else
dfs(row + 1, 1, dep);
}
int main()
{
freopen("1.txt", "r", stdin);
int i, j;
char tmp[15];
memset(arr, 0, sizeof(arr));
for (i = 1; i < 5; i++)
{
scanf("%s", tmp);
for (j = 1; j < 5; j++)
{
if (tmp[j - 1] == '-')
arr[i][j] = 1;
}
}
for (i = 0; i <= 16; i++)
{
IsFind = false;
ans = i;
while (!record.empty()) record.pop_back();
dfs(1, 1, 0);
if (IsFind)
break;
}
if (!IsFind)
printf("Impossible\n");
}