POJ 2965 E - The Pilots Brothers' refrigerator

The game “The Pilots Brothers: following the stripy elephant” has a quest where a player needs to open a refrigerator.

There are 16 handles on the refrigerator door. Every handle can be in one of two states: open or closed. The refrigerator is open only when all handles are open. The handles are represented as a matrix 4х4. You can change the state of a handle in any location [i, j] (1 ≤ i, j ≤ 4). However, this also changes states of all handles in row i and all handles in column j.

The task is to determine the minimum number of handle switching necessary to open the refrigerator.

Input

The input contains four lines. Each of the four lines contains four characters describing the initial state of appropriate handles. A symbol “+” means that the handle is in closed state, whereas the symbol “−” means “open”. At least one of the handles is initially closed.

Output

The first line of the input contains N – the minimum number of switching. The rest N lines describe switching sequence. Each of the lines contains a row number and a column number of the matrix separated by one or more spaces. If there are several solutions, you may give any one of them.

Sample Input

-+--
----
----
-+--

Sample Output

6
1 1
1 3
1 4
4 1
4 3
4 4

题意:一个冰箱有4*4个开关,改变任意一个开关的状态,那么这个开关所在的行和列的开关都要改变,要想打开冰箱,需要所有的开关都是打开的,问操作的最小次数,和输出路径。

分析:我的思路是从第一个点开始搜,在任意一个点上要么选择翻转,要么选择不翻转,如果要翻转还要记录该点的坐标,在搜索之前都要判断一下现在是否满足条件,如果满足条件,则维持一个最小值,

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
char s[10];
int map[10][10];
int vis[105][5],a[105][5];
int cout;
int check()         //判断
{
    for(int i=0;i<4;i++)
        for(int j=0;j<4;j++)
    {
        if(map[i][j]!=1)
            return 0;
    }
    return 1;
} 
void fun(int x,int y)     //进行翻转
{
    map[x][y]=!map[x][y];
    for(int i=0;i<4;i++)
    {
        map[x][i]=!map[x][i];
        map[i][y]=!map[i][y];
    }
}
void dfs(int x,int y,int t)         
{
    if(check())          //符合条件
    {
        if(cout>t)
        {
            cout=t;         //维持一个最小值
            for(int i=0;i<t;i++)     //保存路径
            {
                a[i][0]=vis[i][0];
                a[i][1]=vis[i][1];
            }
            return ;
        }
    }
    if(x>=4||y>=4)
        return ;
    int dx=(x+1)%4;      //坐标更新
    int dy=y+(x+1)/4;     
    dfs(dx,dy,t);        //不翻转
    vis[t][0]=x;         //记录路径
    vis[t][1]=y;
    fun(x,y);
    dfs(dx,dy,t+1);      //翻转
    fun(x,y);
    return ;
}
int main()
{
    for(int i=0;i<4;i++)
    {
        scanf("%s",s);
        for(int j=0;j<4;j++)
        {
            if(s[j]=='+')
                map[i][j]=0;
            else
                map[i][j]=1;
        }
    }
    cout=INF;
    dfs(0,0,0);
    printf("%d\n",cout);
    for(int i=0;i<cout;i++)
        printf("%d %d\n",a[i][0]+1,a[i][1]+1);
}

猜你喜欢

转载自blog.csdn.net/Vace___yun/article/details/81228044