poj_1753 递归+枚举

思路是别人的,自己理解了半天,真是渣渣。对于自己,项目和算法总不能兼得,路还长,年轻人。

思路:

1. 对任意一个格子来说,翻动偶数次等于没翻,翻动奇数次等于翻一次,所以只需考虑翻一次的情况。

2. 一共16个格子,每个格子只有翻和不翻,所以最多16步,最少0步,题目要求最少的步数,所以0——>16枚举,看哪一步先成功就是最优解。

3. 使用dfs,要考虑到树根时如果还没成功,要回溯;回溯时要把棋子再翻回来,再搜。 


#include <iostream>

using namespace std;

bool chess[6][6]={false};
int step;
bool flag;
int r[5]={-1,1,0,0,0};//row up,down,left,right,o
int c[5]={0,0,-1,1,0};//col up,down,left,right,o

//judge whether to the end
bool isOver()
{
	int i,j;
	for(i=1;i<5;i++)
	{
		for(j=1;j<5;j++)
		{
			if(chess[i][j]!=chess[1][1])
			{
				return false;
			}
		}
	}
	return true;
}
//change all adjacent pieces
void flip(int row,int col)
{
	int i;
	for(i=0;i<5;i++)
	{
		chess[row+r[i]][col+c[i]]=!chess[row+r[i]][col+c[i]];
	}
}

void dfs(int row,int col,int deep)
{
	if(deep==step) 
	{
		flag=isOver();
		return;
	}
	if(flag || row==5)
	{
		return;
	}
	flip(row,col);
	if(col<4)
	{
		dfs(row,col+1,deep+1);
	}
	else
	{
		dfs(row+1,1,deep+1);
	}
	flip(row,col);
	if(col<4)
	{
		dfs(row,col+1,deep);
	}
	else
	{
		dfs(row+1,1,deep);
	}
	return;
}

int main()
{
	int i,j;
	char temp;
	//initial
	for(i=1;i<5;i++)
	{
		for(j=1;j<5;j++)
		{
			cin>>temp;
			if('b'==temp)
			{
				chess[i][j]=true;
			}
		}
	}
	//function
	for(step=0;step<=16;step++)
	{
		dfs(1,1,0);
		if(flag)
		{
			break;
		}
	}
	//result
	if(flag)
	{
		cout<<step<<endl;
	}
	else
	{
		cout<<"Impossible"<<endl;
	}
	//system("pause");
	return 0;
}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值