poj_2965 递归+枚举

本题与1753思路一样,区别就在于要记录位置。

deep是当前进行到了哪一步,step是判断用step步是否可以完成,因此记录位置只需在change()后做,回溯的时候虽然会说明上一步无效,但不用修改记录,因为下一次记录会覆盖它。

#include <iostream>
using namespace std;

bool map[4][4]={0};
bool flag=false;
int step;
int res[16][2]={0};

//judge whether to an end
bool isOver()
{
	int i,j;
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			if(map[i][j]==0)
			{
				return false;
			}
		}
	}
	return true;
}

void change(int row,int col)
{
	int i;
	map[row][col]=!map[row][col];
	for(i=0;i<4;i++)
	{
		map[row][i]=!map[row][i];
	}
	for(i=0;i<4;i++)
	{
		map[i][col]=!map[i][col];
	}
}

void dfs(int row,int col,int deep)
{
	if(deep==step)
	{
		flag=isOver();
		return;
	}
	if(flag || row==4)  
    {  
        return;  
    }  
    change(row,col);
	res[deep][0] = row;
	res[deep][1] = col;
    if(col<3)  
    {  
        dfs(row,col+1,deep+1);  
    }  
    else  
    {  
        dfs(row+1,0,deep+1);  
    }  
    change(row,col);  
    if(col<3)  
    {  
        dfs(row,col+1,deep);  
    }  
    else  
    {  
        dfs(row+1,0,deep);  
    }    
}
//1:open,0:close
int main()
{
	char temp;
	int i,j;
	//initial
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			cin>>temp;
			if('-'==temp)
			{
				map[i][j]=1;
			}
		}
	}
	//function
	for(step=1;step<=16;step++)
	{
		dfs(0,0,0);
		if(flag)
		{
			break;
		}
	}
	//result
	cout<<step<<endl;
	for(i=0;i<step-1;i++)
	{
		cout << res[i][0] + 1 << " " << res[i][1] + 1 << endl;
	}
	cout << res[step - 1][0] + 1 << " " << res[step - 1][1] + 1;
	//system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值