poj2965解题报告

摘要:这个题和翻棋盘的题目几乎一样,注意差别在于需要输出路径,因此DFS使得编程方便.注意如果使用BFS,你很难去记录每条路径上所做的决策.

#include "iostream"
#include "string.h"
using namespace std;
int minroute[16],board[16];
int Minstep = 17;
bool success()
{
    for(int i = 0;i<=15;i++)
    {
        if(board[i]!=1)//每一个开关都要处于1(open)
            return false;
    }
    return true;
}
void flip(int index)
{
    int i,j;
    board[index] = !board[index];
    i= index/4, j = 0;
    while(j<=3)
    {
        board[i*4+j] = !board[i*4+j];
        j++;
    }
    j = index-4*i, i = 0;
    while(i<=3)
    {
        board[i*4+j] = !board[i*4+j];
        i++;
    }
}
void Find(int index,int step,int route[16])//top用来存储路径的下标
{
    if(success())
    {
        if(step < Minstep)
        {
            memcpy(minroute,route,sizeof(int)*step);
            minroute[step] = -1;
            Minstep = step;
        }
        return;
    }
    if(  index==16)
    {
        return;
    }
    flip(index);
    route[step] = index;
    Find(index+1,step+1,route);//本次翻转
    flip(index);
    Find(index+1,step,route);//本次不翻转
}
int main()
{
    char c;
    for(int i = 0;i<=3;i++)
    {
        for(int j =0;j<=3;j++)
        {
            cin >> c;
            if(c == '+')
                board[i*4+j] = 0;
            else
                board[i*4+j] = 1;//开
        }
    }

    int route[16];
    int row,col;
    Find(0,0,route);
    cout<<Minstep<<endl;
    for(int index = 0;minroute[index]!=-1;index++)
    {
        row = (minroute[index])/4;
        col = minroute[index] -row*4;
        cout<<row+1<<' '<<col+1<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值