POJ 2965 The Pilots Brothers' refrigerator(枚举+dfs)

本文介绍了解决POJ2965问题的方法,该问题与POJ1573类似,需要通过深度优先搜索算法进行路径记录并翻转特定行列的状态,最终输出最少的操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




http://poj.org/problem?id=2965





分析:

和 POJ 1573 一样的题目  加一下路径记录   翻时候是它所在的行列都要翻 






AC代码:

#include <stdio.h>
#include <string.h>
char map[20][20];
int temp[20][20];
int step;
int flag;
int judge(){
    for (int i=0;i<4;i++){
        for (int j=0;j<4;j++){
            if(map[i][j]!='-')
                return 0;
        }
    }
    return 1;
}
void oper(int x,int y){
    if (map[x][y]=='+')
        map[x][y]='-';
    else    map[x][y]='+';
    for(int i=0;i<4;i++){
    	if (map[x][i]=='+')
    		map[x][i]='-';
    	else  map[x][i]='+';
	} 
	for (int j=0;j<4;j++){
		if (map[j][y]=='+')
    		map[j][y]='-';
    	else  map[j][y]='+';
	}
}
void dfs(int x,int y,int count){
    if(count==step){
    	if((flag=judge())){
    		printf ("%d\n",step);
    		for (int i=0;i<4;i++){
    			for (int j=0;j<4;j++){
    				if(temp[i][j])
    				printf ("%d %d\n",i+1,j+1);
				}
			}	
		}
    	return ;
	}
	if(flag||x==4)
	return;
	oper(x,y);
	temp[x][y]=1;
    if(y<3)
    	dfs(x,y+1,count+1);
    else
    	dfs(x+1,0,count+1); 
	temp[x][y]=0;   
    oper(x,y);
    if(y<3)
    	dfs(x,y+1,count);
    else
    	dfs(x+1,0,count);
}
int main (){
    memset(map,0,sizeof(map));
    for (int i=0;i<4;i++){
        scanf ("%s",map[i]);
    } 
    for(step=0;step<=16;step++){
    	flag=0;
		memset(temp,0,sizeof(temp));
    	dfs(0,0,0);
    	if(flag)
    	break;
	}  
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值