POJ 2965(dfs ,规律)

题目链接:http://poj.org/problem?id=2965

一个冰箱上有4*4共16个开关,改变任意一个开关的状态(即开变成关,关变成开)时,此开关的同一行、同一列所有的开关都会自动改变状态。要想打开冰箱,要所有开关全部打开才行。

     输入:一个4×4的矩阵,+表示关闭,-表示打开;

   输出:使冰箱打开所需要执行的最少操作次数,以及所操作的开关坐标。


dfs

#include<iostream>
using namespace std;
bool board[16];
int is[16]; int js[16];
bool check(){
	for(int i=0;i<16;i++)
		if(!board[i]) return false;
	return true;
}
void init(){
	char a;
	for(int i=0;i<16;i++){
		cin>>a;
		if(a == '+') board[i] = 0;
		else board[i] = 1;
	}
}
void flip(int pos) {//flip
	int i = pos/4;
	int j = pos%4;
	board[pos] = !board[pos];
	for(int m=0;m<4;m++){
		board[i*4+m] = !board[i*4+m]; // row flip
		board[m*4+j] = !board[m*4+j]; // flip column
	}
}
bool dfs(int pos,int step){
	if(check()){
		cout<<step<<endl;
		for(int i=0;i<step;i++)
			cout<<is[i]<<" "<<js[i]<<endl;
		return true;
	}
	if(pos >= 16) return false;
	if(dfs(pos+1,step)) return true;
	flip(pos);
	is[step] = pos/4 + 1; // sign the road;
	js[step] = pos%4 + 1;
	if(dfs(pos+1,step+1)) // after flip 's dfs
		return true;
	flip(pos); // backtracking;
	return false;
}
int main(){
	init();
	dfs(0,0);
}

规律,直接贴一个比较好的解析吧。

http://www.cnblogs.com/Java-tp/p/3873557.html

你可能感兴趣的:(枚举)