POJ 2965(dfs ,规律)
2016-03-28 20:42
351 查看
题目链接: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
一个冰箱上有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
相关文章推荐
- C#编程中枚举类型的使用教程
- 枚举的用法详细总结
- PHP中Enum(枚举)用法实例详解
- c#入门之枚举和结构体使用详解(控制台接收字符串以相反的方向输出)
- 理解C#中的枚举(简明易懂)
- C#枚举中的位运算权限分配浅谈
- C++基础入门教程(四):枚举和指针
- FileShare枚举的使用小结(文件读写锁)
- Java枚举类用法实例
- 枚举窗口句柄后关闭所有窗口示例
- javascript模拟枚举的简单实例
- 深入剖析JavaScript中的枚举功能
- 枚举和宏的区别详细解析
- 深入理解C#中的枚举
- C#实现获取枚举中元素个数的方法
- 结合C++11的新特性来解析C++中的枚举与联合
- java中枚举的详细使用介绍
- java枚举的使用示例
- Java枚举详解及使用实例(涵盖了所有典型用法)
- Java的枚举类型使用方法详解