(poj1.1.2)2965(The Pilots Brothers' refrigerator——DFS+枚举)

149 篇文章 0 订阅

题目大意:将题中所给的图翻转成

----
----
----
----的状态,求需要多少步??

翻转规则是:

1)你可以翻转任何一个棋子

2)该棋子所在的航和列也会跟着翻转。


解题思路:本题和1753的思路很像。。都是使用暴力+DFS+ 枚举,但翻转规则和判断方法有所改变,并且需要记录下路径。

1)判断规则变成

bool judge_all(){
	int i,j;
	for(i = 1 ; i < 5 ; ++i){
		for(j = 1 ; j < 5 ; ++j){
			if( chess[i][j] != false){
				return false;
			}
		}
	}

	return true;
}

2)翻转规则变成

/**
 * 翻转规则是:将自己及其所在行、所在列的棋子都翻转
 */
void flip(int row ,int col){
	int i;
	for(i = 1 ; i < 5 ; ++i){
		chess[row][i] = !chess[row][i];
	}

	for(i = 1 ; i < 5 ; ++i){

		chess[i][col] = !chess[i][col];
	}

	//因为上面chess[row][col]这个棋子翻转了两次,变回了原样,所以这里还要再翻转一次
	chess[row][col] = !chess[row][col];
}

3)需要在翻转时记录路径

flip(row,col);
r[deep] = row;//记录路径的横坐标
c[deep] = col;//记录路径的纵坐标


代码如下:

/*
 * 2965_1.cpp
 *
 *  Created on: 2013年9月13日
 *      Author: Administrator
 */


#include <iostream>
#include <cstdio>

using namespace std;

bool chess[6][6] = {false};
bool flag ;
int step;
int r[20];
int c[20];


bool judge_all(){
	int i,j;
	for(i = 1 ; i < 5 ; ++i){
		for(j = 1 ; j < 5 ; ++j){
			if( chess[i][j] != false){
				return false;
			}
		}
	}

	return true;
}

/**
 * 翻转规则是:将自己及其所在行、所在列的棋子都翻转
 */
void flip(int row ,int col){
	int i;
	for(i = 1 ; i < 5 ; ++i){
		chess[row][i] = !chess[row][i];
	}

	for(i = 1 ; i < 5 ; ++i){

		chess[i][col] = !chess[i][col];
	}

	//因为上面chess[row][col]这个棋子翻转了两次,变回了原样,所以这里还要再翻转一次
	chess[row][col] = !chess[row][col];
}

void dfs(int row , int col , int deep){
	if(deep == step){
		flag = judge_all();
		return ;
	}

	if(flag || row == 5){
		return ;
	}

	flip(row,col);
	r[deep] = row;//记录路径的横坐标
	c[deep] = 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);
	}
}

int main(){
	int i,j;
	char temp;
	flag = false;
	for(i = 1 ; i < 5 ; ++i){
		for(j = 1 ; j < 5 ; ++j){
			cin >> temp;
			if(temp == '+'){
				chess[i][j] = true;
			}
		}
	}


	for(step = 0 ; step <= 16 ; ++step){
		dfs(1,1,0);
		if(flag){
			break;
		}
	}

	cout<<step<<endl;
	for(i = 0 ; i < step ; ++i){
		cout<<r[i]<<" "<<c[i]<<endl;
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值